我的帐户控制器中的C#存在问题.
I'm having an issue in C# in my accountcontroller.
public class Authenticateuser { int Userid = 0; static string connstring = ConfigurationManager.ConnectionStrings["dbPCTECH"].ConnectionString; public MySqlConnection connection = new MySqlConnection(connstring); Connection.open;connection.open正在引发异常,它不在当前上下文中.是什么原因造成的?我曾尝试过更改名称,等等.我从来没有遇到过这个问题.
connection.open is raising the exception, that it's not in the current context. What's causing this? I have tried changing names, etc. I've never had this issue.
推荐答案三个主要问题:
在C#中, Connection 与 connection 不同.有时候,您可能希望使用不同的大小写来区分两个成员,例如完整的Properties,但是除此之外, connection 和 conNectIOn 不好,即使它会工作.
In C#, Connection is different than connection. There are times when you would want to use the different casing to differentiate between two members, such as full Properties, but besides that, it is bad to have connection and conNectIOn, even though it wll work.
此外,要调用函数或方法,您需要在名称末尾使用(),因此您需要执行 connection.Open();
Also, to call a function or method, you need to use the () at the end of the name, so you'd do connection.Open();
编辑:问题3有点复杂.这是您的课程:
EDIT: Problem 3 is a bit more complicated. Here's your class:
public class Authenticateuser { public MySqlConnection connection = new MySqlConnection(connstring); private static string connstring = ConfigurationManager .ConnectionStrings["dbPCTECH"].ConnectionString; private int Userid = 0; connection.Open; }我将代码重构得更常规一些,顶部是 public 成员,底部是 private 成员, static 上面的成员都是非静态的.如果您不使用 private ,它将默认设置为 private ,但我更愿意在键入时使用明确的字词.
I refactored the code a little bit to be in a more conventional order, public members on top, private members on bottom, static members above non-static. If you don't use private it will default to private but I prefer being explict in the typing.
无论如何,这个问题与不能在类体内直接调用函数有关.只能在其中写入字段,属性和方法.您需要做的是将其包装在另一个函数中,如下所示:
Anyways, this problem has to do with the fact that functions can't be called inside class bodies directly. Only fields, properties and methods can be written there. What you need to do, is wrap it inside another function, like so:
public class Authenticateuser { public MySqlConnection connection = new MySqlConnection(connstring); private static string connstring = ConfigurationManager .ConnectionStrings["dbPCTECH"].ConnectionString; private int Userid = 0; public Open() => connection.Open(); }也是
public Open() => connection.Open();与以下内容完全相同:
public Open() { connection.Open(); }只是清洁工.这应该工作.然后,您可以这样称呼它:
Just cleaner. This should work. You then call it like this:
var auth = new Authenticatuser(); auth.Open();通常认为做 auth.Open(); 比做 auth.connection.Open(); 更好.这是因为,在现实生活中,您不会告诉狗的腿移动,而是告诉狗移动,而狗却告诉狗自己的腿移动.
It is also generally considered better to do auth.Open(); than auth.connection.Open();. This is because, in real life, you don't tell the dogs legs to move, you tell the dog to move, and the dog tells it's own legs to move.
更多推荐
在当前上下文中不存在
发布评论