And*_*are 22
成员变量是类型的成员,属于该类型的状态.局部变量不是类型的成员,表示本地存储而不是给定类型的实例的状态.
然而,这一切都非常抽象.这是一个C#示例:
class Program
{
static void Main()
{
// This is a local variable. Its lifespan
// is determined by lexical scope.
Foo foo;
}
}
class Foo
{
// This is a member variable - a new instance
// of this variable will be created for each
// new instance of Foo. The lifespan of this
// variable is equal to the lifespan of "this"
// instance of Foo.
int bar;
}
Run Code Online (Sandbox Code Playgroud)
成员变量有两种:实例和静态.
实例变量的持续时间与类的实例一样长.每个实例将有一个副本.
静态变量和类一样长.整个班级有一份副本.
局部变量在方法中声明,并且只持续到方法返回:
public class Example {
private int _instanceVariable = 1;
private static int _staticvariable = 2;
public void Method() {
int localVariable = 3;
}
}
// Somewhere else
Example e = new Example();
// e._instanceVariable will be 1
// e._staticVariable will be 2
// localVariable does not exist
e.Method(); // While executing, localVariable exists
// Afterwards, it's gone
Run Code Online (Sandbox Code Playgroud)