Reference types in depth

十年热恋 提交于 2021-01-29 16:45:22

问题


I understand that the semantics of equality checking changes based on whether you are checking value types or rference types. Aren't reference types just a higher level pointer? What exactly is happening when using a reference type? Is all the dereferencing, upcasting etc just being handled by the runtime now?


回答1:


Yes, exactly, reference types are just "pointers" to memory that is managed by the garbage collector.

C++:

MyClass* mc = new MyClass();
Myclass* mc2 = mc;

mc == mc2 // true, points at the same memory address

C#:

MyClass mc = new MyClass();
MyClass mc2 = mc;

mc == mc2 // also true for the same reason



回答2:


C# equality operator for reference types checks whether or not the two operands reference the same object, unless the equality operator is overriden:

http://msdn.microsoft.com/en-us/library/53k8ybth.aspx

For more information on Object.Equals and equality operator == have a look here:

http://msdn.microsoft.com/en-us/library/ms173147.aspx




回答3:


Check out here: http://www.albahari.com/valuevsreftypes.aspx




回答4:


Eric Lippert has a great post (also explaining the relationships between reference, pointer and address)... http://blogs.msdn.com/ericlippert/archive/2009/02/17/references-are-not-addresses.aspx




回答5:


The reference is a data structure that is used to manage the object in memory. If you are familiar with C then you may have used buffered IO routines like fprintf(). If you look at fprintf's FILE handle in the debugger you see that the pointer to the data is only one implementation dependent detail of the data structure. The C library manages all the memory allocation required for fprintf().

Same is true for references. The location of the actual data can change, unless you pin the object using the GCHandle. However, pinning the object make the system less efficient. You only would do that to interface buffers with unmanaged code. Also: I agree with timvw about the Eric Lippert post he linked, but I don't have enough rep to vote.



来源:https://stackoverflow.com/questions/1938301/reference-types-in-depth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!