为什么这个打印'7‘的代码试图理解Stack和Heap是什么样子的,以及它在内存分配中是什么样子的
public static void Main()
{
Cls a = new Cls();
a.v = 3;
Func(a);
Console.WriteLine(a.v);
}
class Cls
{
public int v;
}
static void Func(Cls a)
{
a.v = 7;
a = new Cls();
a.v = 2;
}如果你能把堆栈和堆与内存结合起来,那将是非常值得感谢的。
发布于 2016-06-29 15:13:03
static void Func(Cls a)
{
a.v = 7; <----- This is modifying the Cls you create in Main function
a = new Cls();
a.v = 2; <----- This is a new and locally referenced Cls whose value is neither returned to the main function nor is a global variable
}发布于 2016-06-29 14:57:11
您正在传递指向第一个日志服务实例的指针。第二个是在youre函数中创建的,它是一个完全不同的对象。
换句话说,您打印的是第一个对象的属性值,也就是a In Main()所指向的对象。
当您将主变量a重新赋值给函数内部的新对象时,a inside ()仍然指向原始对象。
我不确定我有没有很好的解释...:)或者我甚至误解了这个问题?
https://stackoverflow.com/questions/38092309
复制相似问题