https://blog.csdn.net/c1sdn19/article/details/88402893
https://www.cnblogs.com/TivonStone/archive/2011/11/24/2261090.html
https://jonskeet.uk/csharp/memory.html 这篇文章已经讲解的很清楚了。
https://stackoverflow.com/questions/4853213/are-structs-always-stack-allocated-or-sometimes-heap-allocated
总结:
1、结构体作为单独的类型出现的时候,new或者是声明,都是分配在栈上的。
2、结构体作为引用类型的成员时,内存分配在堆上。
struct PairOfInts
{
static int counter = 0;
public int a;
public int b;
internal PairOfInts(int x, int y)
{
a = x;
b = y;
counter++;
}
}
class Test
{
PairOfInts pair;
string name;
Test(PairOfInts p, string s, int x)
{
pair = p;
name = s;
pair.a += x;
}
static void Main()
{
PairOfInts z = new PairOfInts(1, 2);
Test t1 = new Test(z, "first", 1);
Test t2 = new Test(z, "second", 2);
Test t3 = null;
Test t4 = t1;
// XXX
}
}
1、z栈上
2、t1本身在栈上,t1所指的内容在堆上,t1的成员pair在堆上。
3、t2本身在栈上,t2所指的内容在堆上,t2的成员pair在堆上。
4、t3本身在栈上,t3指向的内容为null。
5、t4本身在栈上,t4和t1所指向的内容为同一块堆上的内存。