【发布时间】:2012-09-10 19:45:44
【问题描述】:
在网上阅读的同时,我了解到静态变量总是具有相同的内存地址。因此在编译程序时,编译器将决定分配给静态变量的内存地址。 阅读让我想到了当你这样做时会发生什么:
class Foo {}
class Program
{
public static Foo someStaticVar;
static void Main(string[] args)
{
Foo localVariable = new Foo();
int x = 4;
someStaticVar = localVariable; // is someStaticVariable still will have the same address?
}
// variable x will be pushed of the stack
// localVariable will be pushed of the stack
// what happens then with someStatic var?
}
我还了解到,在方法中声明变量时,它们将在创建时被压入堆栈,并在方法返回时弹出堆栈。如果这一切都是真的,那么 someStaticVar 应该消失,但它不会。
我确定我一定理解有误。或者也许在线someStaticVar = localVariable; 正在执行该对象的深拷贝,但我对此表示怀疑,因为互联网上有很多关于如何对对象进行深拷贝的问题,它们与这种方法有很大不同。
【问题讨论】:
-
“内存地址”在托管语言中毫无意义。所以,不,编译器不会为 C# 中的任何变量预先分配内存地址。
标签: c# static heap-memory stack-memory