开发者

Reference type being an object?

In my previous question (regarding adding items to ArrayList) one of the posters w开发者_运维知识库rote that "reference is already an object" - how it was meant? I do not get it. I thought reference is just an address of the object that I can pass:

object X=5;

object A=X; //here I am assigning reference to X so both are pointing to copy of 5

Also with the ArrayList example, it actually stores references..but again I got confused with comment "System.Object" reference type. What does it mean?

I would be very grateful for simple examples. I do understand difference between value types and ref.types, however this is something I cannot figure out altough I know it works.


What you've done in your code is taken a value type and "boxed" it, so now it is a reference type on the heap which contains the value "5". I would recommend you start out by trying to get an understanding of value/reference types in C#, mutability/immutability, and boxing/unboxing.

Here's a good link to get you started: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

Jon Skeet's book "C# in depth" also does a good job on this (section 2.3.4).

Hope that helps.


The first line is a boxing operation that creates a boxed copy of the integer 5. The reference to this new object is stored in X

In the second line, the value of the reference (which is broadly the address, but addresses and references are logically different) is copied into A, as this is just a "ldloc,stloc" copy. There is only a single object in this scenario; the boxed object created in the first line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜