根据
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.