【发布时间】:2015-10-21 21:47:04
【问题描述】:
在`类变量、成员变量、局部变量和全局变量之间进行分类?
【问题讨论】:
-
This 应该是一个很好的解释。
-
局部变量在块内声明,如方法块或
for块,它们的生命周期由包含它们的大括号 { } 定义。上面的链接是一个很好的解释,但并没有真正进入“本地”的定义。
在`类变量、成员变量、局部变量和全局变量之间进行分类?
【问题讨论】:
for 块,它们的生命周期由包含它们的大括号 { } 定义。上面的链接是一个很好的解释,但并没有真正进入“本地”的定义。
类定义中静态定义的变量是类变量。
public MyClass
{
static int a; // class variable
}
在函数(方法)中声明的变量是局部变量。
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;
【讨论】:
比 cmets 中关于“局部”变量的链接问题更进一步......
“局部”变量是一个生命周期由包含它的大括号定义的变量。例如:
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 等事物的范围。它们定义了 local 范围。
为了完整起见,这里是一个类/成员变量:
public class SomeClass
{
public int SomeVariable;
}
这里,SomeVariable 定义在SomeClass 范围内,可以通过SomeClass 类的实例进行访问:
SomeClass sc = new SomeClass();
sc.SomeVariable = 10;
人们称static variables为类变量,但我不同意这个定义,静态类就像单例实例,我喜欢将它们视为成员变量。
还强烈建议您在类外公开数据时使用属性而不是公共可变成员。
【讨论】: