根据 this msdn 文档
If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method.
那么为什么下面的代码会导致两种不同的方法调用结果 Equals
方法返回 True 和 ReferenceEquals
方法返回 false,即使obj
和 obj1
是引用类型,因为 IsClass
属性返回 true。
using System;
public class Program
{
public static void Main()
{
var obj = new { a = 1, b = 1 };
var obj1 = new { a = 1, b = 1 };
Console.WriteLine("obj.IsClass: " + obj.GetType().IsClass);
Console.WriteLine("object.ReferenceEquals(obj, obj1): " + object.ReferenceEquals(obj, obj1));
Console.WriteLine("obj.Equals(obj1): " + obj.Equals(obj1));
}
}
输出:
obj.IsClass: True
object.ReferenceEquals(obj, obj1): False
obj.Equals(obj1): True
最佳答案
obj
和 obj1
引用 2 个不同的对象,因此 object.ReferenceEquals()
将返回 false。
Equals()
返回 true,因为编译器为匿名类型实现了 Equals()
。如果两个对象的所有属性都具有相同的值,它将返回 true。
关于c# - 为什么 Equals 和 ReferenceEquals 方法的结果不同,即使变量是引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870174/