所以我有一個類重寫Equals(object obj)和GetHashCode()以及實現IEquatable。爲了使這種類型的工作在檢查平等時更自然一些,我認爲,嘿,我會超負荷平等運算符和不平等運算符,無後顧之憂......重載的操作符參數始終爲空
呃哦,憂慮...考慮以下 - 其中兩個實例的myType不爲空:
if (myType != container.myType) //NullReferenceException
{
//never get here
}
//never get here either
現在,容器是另一個類以保存其中用於緩存項以外的東西的的myType一個實例。
下面是對的myType實際的(相關)代碼:
public class MyType : IEquatable<MyType>
{
public static bool operator ==(MyType myTypeA, MyType myTypeB)
{
return myTypeA.Equals(myTypeB);
}
public static bool operator !=(MyType myTypeA, MyType myTypeB)
{
return !(myTypeA == myTypeB);
}
public override bool Equals(object obj)
{
if (obj != null && obj is MyType)
{
return Equals((MyType)obj);
}
return false;
}
public bool Equals(MyType other)
{
if (other != null)
{
return other.ToString() == ToString();
}
return false;
}
}
在這方面的經驗嗎?
謝謝。
你能後的堆棧跟蹤?因爲如果你得到一個NRE,東西必須是空的。你是如何驗證這兩個參數都不爲空的? – 2010-10-03 15:10:50