一个成员变量和一个局部变量有何区别?
它们是相同的吗?
它们是相同的吗?
本地变量是在函数中声明的变量。
成员变量是在类定义中声明的变量。
成员变量是类型的成员,属于该类型的状态。局部变量不是类型的成员,代表本地存储而不是给定类型实例的状态。
然而,这一切都很抽象。以下是一个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;
}
有两种成员变量:实例变量和静态变量。
实例变量的生命周期与类的实例相同,每个实例都有一个副本。
静态变量的生命周期与类相同,整个类只有一个副本。
局部变量在方法中声明,仅在方法返回前存在:
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
public class Foo
{
private int _FooInt; // I am a member variable
public void Bar()
{
int barInt; // I am a local variable
//Bar() can see barInt and _FooInt
}
public void Baz()
{
//Baz() can only see _FooInt
}
}
本地变量是您在函数中声明的变量。它的生命周期仅限于该函数。
成员变量是您在类定义中声明的变量。它的生命周期仅限于该类。它是全局变量。可以被同一类中的任何函数访问。