【发布时间】:2021-10-22 06:37:55
【问题描述】:
成员变量和局部变量有什么区别?
它们是一样的吗?
【问题讨论】:
-
请记住,因为您只标记了编程,您会收到各种语言的回复。
标签: variables
成员变量和局部变量有什么区别?
它们是一样的吗?
【问题讨论】:
标签: variables
成员变量是一个类型的成员并且属于该类型的状态。局部变量不是类型的成员,它表示本地存储而不是给定类型的实例的状态。
然而,这一切都非常抽象。这是一个 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
}
}
【讨论】:
一个成员变量属于一个对象...有状态的东西。局部变量只属于您所在范围的符号表。但是,它们将在内存中表示,就像计算机没有类的概念一样......它只看到代表指令的位。局部变量和成员变量都可以在栈上或堆上。
【讨论】: