类变量,成员变量和局部变量之间的区别,全局变量
我想在DotNet中应用代码标准,我如何通过在DotNet C#中的整个项目之间对Class variable, Member variable, and Local variable and Global Variable
进行分类,将Camel and Pascal Notation
写入我的代码。 请举例说明。
类定义中定义的变量static是类变量。
public MyClass { static int a; // class variable }
在函数(Method)中声明的变量是局部变量。
public class MyClass { static void Main() { string name; //local variable } }
在类定义中声明的变量,当实例化类时,这些变量将是成员变量
public class MyClass { int a; // here they are local variable of class body. int b; } //create instance of class MyClass mc = new MyClass(); mc.a = 10; //these are member variables mc.b = 11;
在关于“本地”变量的评论中比关联问题更进一步……
“本地”变量是一个变量,其生命周期由包含它的大括号定义。 例如:
void SomeMethod() { int a = 0; //a is a local variable that is alive from this point down to } }
但是还有其他类型的局部变量,例如:
void SomeMethod() { for (int i = 0; i < 10; i++) { int a = 0; //a and i are local inside this for loop } //i and a do not exist here }
甚至这样的东西都是有效的(但不推荐):
void SomeMethod() { int x = 0; { int a = 0; //a exists inside here, until the next } //x also exists in here because its defined in a parent scope } //a does not exist here, but x does }
{
和}
是作用域定界符。 他们定义了某种范围。 在方法下定义时,它们定义属于该方法的代码的范围。 它们还定义了for
, if
, switch
, class
等等的范围。它们定义了一个局部范围。
为了完整性,这是一个类/成员变量:
public class SomeClass { public int SomeVariable; }
这里, SomeVariable
在SomeClass
范围中定义,可以通过SomeClass
类的实例访问:
SomeClass sc = new SomeClass(); sc.SomeVariable = 10;
人们调用static
变量类变量,但我不同意定义,静态类就像单例实例,我喜欢将它们视为成员变量。
强烈建议您在类外部公开数据时使用属性而不是公共可变成员。