简体   繁体   English

引用类型是对象?

[英]Reference type being an object?

In my previous question (regarding adding items to ArrayList) one of the posters wrote that "reference is already an object" - how it was meant? 在我之前的问题中(关于向ArrayList添加项目),其中一位张贴者写道:“引用已经是一个对象” –它的含义是什么? 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. 同样在ArrayList示例中,它实际上存储了引用。但是,我再次对注释“ System.Object”引用类型感到困惑。 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. 我确实了解值类型和ref.types之间的区别,但是我无法完全理解这一点,尽管我知道它是可行的。

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". 您在代码中完成的操作将采用值类型并将其“装箱”,因此现在它是堆上的引用类型,其中包含值“ 5”。 I would recommend you start out by trying to get an understanding of value/reference types in C#, mutability/immutability , and boxing/unboxing . 我建议您首先尝试了解C#中的值/引用类型可变性/不可变性装箱/拆箱

Here's a good link to get you started: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx 这是一个入门的好链接: http : //msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx

Jon Skeet's book "C# in depth" also does a good job on this (section 2.3.4). 乔恩·斯基特(Jon Skeet)的著作“ C#in depth”在这方面也做得很好(第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 第一行是装箱操作,它将创建整数5的装箱副本 。对此新对象的引用存储在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. 在第二行中, 引用 (大致是地址,但是地址和引用在逻辑上是不同的)被复制到A中,因为这只是“ ldloc,stloc”副本。 There is only a single object in this scenario; 在这种情况下,只有一个对象。 the boxed object created in the first line. 在第一行中创建的框对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM