成员变量和局部变量之间有什么区别?

Chi*_*hin 23 variables

成员变量和局部变量之间有什么区别?

它们是一样的吗?

ufu*_*gun 36

局部变量是您在函数中声明的变量.

成员变量是您在类定义中声明的变量.


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)

  • 堆栈是一个实现细节.是的,许多语言在调用堆栈上存储局部变量,但是根据定义,它与局部变量_is_没有任何关系.我只包含一个代码示例来帮助理解我所谈论的抽象概念. (4认同)
  • 你还应该提一下堆栈的内容 (2认同)
  • 我喜欢称成员变量"字段"只是为了减少"变量"这个词的使用.:) (2认同)

Joh*_*ers 5

成员变量有两种:实例和静态.

实例变量的持续时间与类的实例一样长.每个实例将有一个副本.

静态变量和类一样长.整个班级有一份副本.

局部变量在方法中声明,并且只持续到方法返回:

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)