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

时间:2009-07-24 13:38:42

标签: variables

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

他们是一样的吗?

7 个答案:

答案 0 :(得分:33)

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

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

答案 1 :(得分:21)

成员变量是类型的成员,属于该类型的状态。局部变量不是类型的成员,而是表示本地存储而不是给定类型的实例的状态。

然而,这一切都非常抽象。这是一个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;
}

答案 2 :(得分: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

答案 3 :(得分:2)

局部变量是您在函数中声明的变量。它的生命周期仅在该函数上。

成员变量是你在类定义中声明的变量。它的生命周期只在该类中。它是全局变量。它可以被同一个类中的任何函数访问。

答案 4 :(得分:1)

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
    }
}

答案 5 :(得分:1)

  • 在方法中声明的变量是"局部变量"
  • 在类中声明的变量不在任何方法中是"成员变量"(全局变量)。
  • 在类中声明的变量不在任何方法中并定义为static是"类变量"。

答案 6 :(得分:0)

成员变量属于对象...具有状态的东西。一个局部变量只属于你所处的任何范围的符号表。但是,它们将在内存中表示,就像计算机没有类的概念一样......它只是看到代表指令的位。局部变量和成员变量都可以在堆栈或堆上。

相关问题