using
System;
using
System.Collections.Generic;
![](/Images/OutliningIndicators/None.gif)
namespace
abcd
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
class Program
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
S s;
struct S
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public int x; //public int x = 0 编译错误?解释为什么
}
![](/Images/OutliningIndicators/InBlock.gif)
C c = new C();
class C
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public int x = 0;
}
void print()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine("{0}/t{1}", s.x, c.x);
}
![](/Images/OutliningIndicators/InBlock.gif)
void Foo1(S s, C c)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s.x++;
c.x++;
print();
}
![](/Images/OutliningIndicators/InBlock.gif)
void Foo2(S s, C c)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s = new S();
c = new C();
print();
}
![](/Images/OutliningIndicators/InBlock.gif)
void Foo3(ref S s, ref C c)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s.x++;
c.x++;
print();
}
![](/Images/OutliningIndicators/InBlock.gif)
void Foo4(ref S s, ref C c)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s = new S();
c = new C();
print();
}
![](/Images/OutliningIndicators/InBlock.gif)
void Test()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Foo1(s, c);
Foo2(s, c);
Foo3(ref s, ref c);
Foo4(ref s, ref c);
// 输出结果,解释为什么:
// 0 1
// 0 1
// 1 2
// 0 0
![](/Images/OutliningIndicators/InBlock.gif)
List<S> l1 = new List<S>();
l1.Add(s);
//l1[0].x++; 编译错误?解释为什么
![](/Images/OutliningIndicators/InBlock.gif)
S[] l = new S[1];
l[0] = new S();
l[0].x++;
// 数组OK,解释为什么
![](/Images/OutliningIndicators/InBlock.gif)
List<C> l2 = new List<C>();
l2.Add(c);
l2[0].x++;
// OK,解释为什么
}
![](/Images/OutliningIndicators/InBlock.gif)
static void Main()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
new Program().Test();
}
}
}
解释每一个为什么,并且画出对象在内存中的布局变化图!