Struct(Value Types) And Class(Reference Type)

Struct(Value Types) And Class(Reference Type)

只是記錄一個小實驗。平常很少使用struce,所以對他也不是很了解,最近看了書才

開始比較熟悉一點XD

struct person
{
	public int Age;
}
public class person2    
{
	public int Age;
}
public static void Test()
{
	person p;
	person2 p2 = new person2();
	p.Age = 8;
	p2.Age = 8;
	Console.WriteLine("p1=" + p.Age.ToString());
	Console.WriteLine("p2=" + p2.Age.ToString());
	test2(p);
	test3(p2);
	Console.WriteLine("p1=" + p.Age.ToString());
	Console.WriteLine("p2=" + p2.Age.ToString());
}
private static void test2(person p)    
{
	p.Age = 10;
	Console.WriteLine("p1=" + p.Age.ToString());
}

private static void test3(person2 p)    
{
	p.Age = 10;
	Console.WriteLine("p2=" + p.Age.ToString());
}

結果:

p1=8
p2=8
p1=10
p2=10
p1=8
p2=10

所以Struce 是value types 而 class是reference types!