C#默认等于行为。
示例
Equals在Object类本身中声明。
public virtual bool Equals(Object obj);
默认情况下,Equals具有以下行为:
如果实例是引用类型,则Equals仅当引用相同时才返回true。
如果实例是值类型,则Equals仅当类型和值相同时才返回true。
string是一个特例。它的行为类似于值类型。
namespace ConsoleApplication { public class Program { public static void Main(string[] args) { //areFooClassEqual:否 Foo fooClass1 = new Foo("42"); Foo fooClass2 = new Foo("42"); bool areFooClassEqual = fooClass1.Equals(fooClass2); Console.WriteLine("fooClass1 and fooClass2 are equal: {0}", areFooClassEqual); //False //areFooIntEqual:正确 int fooInt1 = 42; int fooInt2 = 42; bool areFooIntEqual = fooInt1.Equals(fooInt2); Console.WriteLine("fooInt1 and fooInt2 are equal: {0}", areFooIntEqual); //areFooStringEqual:真 string fooString1 = "42"; string fooString2 = "42"; bool areFooStringEqual = fooString1.Equals(fooString2); Console.WriteLine("fooString1 and fooString2 are equal: {0}", areFooStringEqual); } } public class Foo { public string Bar { get; } public Foo(string bar) { Bar = bar; } } }