//值类型和引用类型区别示例
using System;
class RefTypeRectangle //定义一个引用类型(类属于引用类型)
{
public int Height;
public int Width;
}
struct ValTypeRectangle//定义一个值类型(结构属于值类型)
{
public int Height;
public int Width;
}
class RefValTest
{
public static int Main()
{
RefTypeRectangle rect1 = new RefTypeRectangle();
rect1.Width = 10;
rect1.Height = 15;
RefTypeRectangle rect2 = rect1;
Console.WriteLine("Dimensions of rect2 are " + rect2.Width + "x" + rect2.Height);
//输出 Dimensions of rect 2 are 10x15
Console.WriteLine("changing dimensions of rect1...");
rect1.Width = 20;
rect1.Height = 25;
Console.WriteLine("Dimensions of rect2 now are " + rect2.Width + "x" + rect2.Height);
//输出 Dimensions of rect 2 are 20x25。
//rect1的值得改变rect2的值也跟着该变了,因为变量rect2和rect1仅对内存中同一位置的引用
ValTypeRectangle rect3 = new ValTypeRectangle();
rect3.Width = 10;
rect3.Height = 15;
ValTypeRectangle rect4 = rect3;
Console.WriteLine("Dimensions of rect4 are " + rect4.Width + "x" + rect4.Height);
//输出 Dimensions of rect
Console.WriteLine("changing dimensions of rect3...");
rect3.Width = 20;
rect3.Height = 25;
Console.WriteLine("Dimensions of rect4 now are " + rect4.Width + "x" + rect4.Height);
//输出 Dimensions of rect 4 are 10x15。
//rect3的值得改变,rect4的值没有发生变化,因为rect4是值类型,它有自己的值。
Console.ReadLine();
return 0;
}
}