[csharp] public class MyClass { public int ID; /*public static bool operator ==(MyClass c1, MyClass c2) { //下面這段代碼中的“==”調用會進入遞歸,直至崩潰 if (c1 == null || c2 == null) { return c1 == c2; } return c1.ID == c2.ID; } public static bool operator !=(MyClass c1, MyClass c2) { //下面這段代碼中的“==”調用會進入遞歸,直至崩潰 if (c1 == null || c2 == null) { return c1 != c2; } return c1.ID != c2.ID; }*/ //正確的方法 public static bool operator ==(MyClass c1, MyClass c2) { //將c1對象轉為object再進行判斷 //這裡的object.Equals(c1, null)也可以寫成 //c1 as object == null if (object.Equals(c1, null) || object.Equals(c2, null)) { return object.Equals(c1, c2); } return c1.ID == c2.ID; } public static bool operator !=(MyClass c1, MyClass c2) { if (object.Equals(c1, null) || object.Equals(c2, null)) { return !object.Equals(c1, c2); } return c1.ID != c2.ID; } }