本文共 2805 字,大约阅读时间需要 9 分钟。
1 首先看下这个表
Intriguing Question Value Type Reference Type
Where is this type allocated? Allocated on the stack. Allocated on the managed heap.
How is a variable represented? Value type variables are local Reference type variables are
copies. pointing to the memory occupied by the allocated instance.What is the base type? Must derive from Can derive from any other type
System.ValueType. (except System.ValueType), as long as that type is not “sealed” Can this type function as a No. Value types are always Yes. If the type is not sealed, itbase to other types? sealed and cannot be may function as a base to other extended. types.What is the default parameter Variables are passed by value Variables are passed by reference
passing behavior? (i.e., a copy of the variable is (e.g., the address of the passed into thecalled variable is passed into the called
function). function).Can this type override No. Value types are never Yes, indirectly 。
System.Object.Finalize()? placed onto the heap therefore do not need to be finalized.Can I define constructors for Yes, but the default constructor But of course!
this type? is reserved (i.e., your customconstructors must all have arguments).
When do variables of this When they fall out of the When the managed heap is
type die? defining scope. garbage collected.
现在来详细说说
在C#中 数据类型有2中 1是值类型 2是引用类型值类型通常被分配在栈中 而引用类型通常需要用到new(后面会说说它的用法)关键字在堆上分配一个空间我们知道在堆上的数据是有GC来管理的 当该变量不用了 GC就会将其处理掉.但GC并不处理栈中的数据。(后面会详细说明GC的处理过程的)。 注意:我们知道结构属于值类型 我们运用它时并不需要new关键字去创建它但如果结构中有引用类型时 我们必须用new关键字创建它 为它分配空间。class ShapeInfo{ public string infoString; public ShapeInfo(string info) { infoString = info; }}
struct MyRectangle
{ public ShapeInfo rectInfo; public int top, left, bottom, right;public MyRectangle(string info)
{ rectInfo = new ShapeInfo(info); top = left = 10; bottom = right = 100;}}static void Main(string[] args){Console.WriteLine("-> Creating r1");
MyRectangle r1 = new MyRectangle("This is my first rect");//用new创建值类型 }我们通常知道对于值类型相互赋值属于深拷贝,而对引用类型之间赋值为浅拷贝,
如果对上面的例子我们应该这么看待呢把Main数中的更新一下 运行就知道结果了static void Main(string[] args){ // Create the first MyRectangle.Console.WriteLine("-> Creating r1");MyRectangle r1 = new MyRectangle("This is my first rect");// Now assign a new MyRectangle to r1.Console.WriteLine("-> Assigning r2 to r1");MyRectangle r2;r2 = r1;// Change values of r2.Console.WriteLine("-> Changing all values of r2");r2.rectInfo.infoString = "This is new info!";r2.bottom = 4444;// Print valuesConsole.WriteLine("-> Values after change:");Console.WriteLine("-> r1.rectInfo.infoString: {0}", r1.rectInfo.infoString);Console.WriteLine("-> r2.rectInfo.infoString: {0}", r2.rectInfo.infoString);Console.WriteLine("-> r1.bottom: {0}", r1.bottom);Console.WriteLine("-> r2.bottom: {0}", r2.bottom);}可以看到对引用类型来说还是浅拷贝转载地址:http://ycmvi.baihongyu.com/