简体   繁体   中英

How ReferenceEquals can understand references belong same object?

我只是.NET的一些类和方法的好奇背景所以我只是想知道ReferenceEquals方法如何理解2个引用属于同一个对象?

Because 'the same object' means 'same place in memory' and the operation can simply check the 'address' value of a reference.

Not that you can easily get at that value , but then you never need to.

The reference is basically a 32-bit integer which points to a location in the heap where the object is stored, so ReferenceEquals can simply compare the two integers values and check if they're the same.

Mind you for value types, ReferenceEqual will ALWAYS fail! ValueType overrides the virtual Object.Equals method to compare all member variables in a derived type rather than the reference.

With out knowing the runtime names and types of the member variables, the default implementation of ValueType.Equals relies on the use of reflection and reflection as we all know, is slow. As a general rule of thumb, it's recommended that you ALWAYS override the ValueType.Equals method when creating your custom value type and you should strongly consider overloading the == and != operators too whilst you're at it!

Because they have the same value. Just like two pointers in an unmanaged app point to the same object if they have the same value.

ReferenceEqulas checks the memory location is same or not

 class MyClass {

       static void Main() {
          object o = null;
          object p = null;
          object q = new Object();

          //Here o and p not referring to any location.so result true
          Console.WriteLine(Object.ReferenceEquals(o, p));
          p = q; // here p's memory location is mapping to q.So both referring to same memory    location. so result is true.
          Console.WriteLine(Object.ReferenceEquals(p, q));
            //Here the p and o are in different memory location so the result is false
          Console.WriteLine(Object.ReferenceEquals(o, p));
       }
    }

我怀疑它正在检查引用是否指向内存中的同一个对象,即是否为两个对象引用了相同的地址。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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