[英]Please explain the technique used in this code to test Object Equality and Identity
請解釋此代碼中用於測試對象平等和身份的技術。
更好,如果您能為我提供任何網站鏈接/書籍參考,以供詳細討論。
[Serializable]
public abstract class BusinessObject<T> : IBusinessObject where T : BusinessObject<T>
{
private int? requestedHashCode;
public virtual int ID { get; set; }
public virtual bool Equals(IBusinessObject other)
{
if (null == other || !GetType().IsInstanceOfType(other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
bool otherIsTransient = Equals(other.ID, default(T));
bool thisIsTransient = IsTransient();
if (otherIsTransient && thisIsTransient)
{
return ReferenceEquals(other, this);
}
return other.ID.Equals(ID);
}
protected bool IsTransient()
{
return Equals(ID, default(T));
}
public override bool Equals(object obj)
{
var that = obj as IBusinessObject;
return Equals(that);
}
public override int GetHashCode()
{
if (!requestedHashCode.HasValue)
{
requestedHashCode = IsTransient() ? base.GetHashCode() : ID.GetHashCode();
}
return requestedHashCode.Value;
}
}
什么是瞬態物體?
other
是否是與當前對象相同類型的實例。 如果沒有,他們就不平等 other
對象和當前對象是否是同一個實例。 如果他們是,顯然他們是平等的 other
對象和當前對象都是暫時的(即尚未持久化),則它們沒有ID,因此無法通過ID進行比較。 相反,它們通過參考進行比較。 (正如Marc Gravell在評論中指出的那樣,檢查對象是否是瞬態的測試被破壞;將int與默認值(T)進行比較是沒有意義的) 我認為代碼試圖做的是“它還有ID嗎”,即“瞬態”對象可能(如果我正確讀取代碼的意圖)是尚未保存到DB的那個。 然后將相等定義為:
不幸的是,實現看起來完全破壞了,因為當T
是完全不同的東西( BusinessObject<T>
)時, Equals(ID, default(T))
毫無意義 - 因此default(T)
將始終為null
, ID
將永遠不為null
(它是不可空的)。 所以沒有任何東西可以報告為瞬態。
另外,這段代碼:
if (null == other || !GetType().IsInstanceOfType(other))
非常低效。 我懷疑涉及一些as
將遠遠最好,但再次:代碼看起來如此... ...折磨,我很厭惡第二猜測意圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.