[英]C# List comparison between custom objects
Pair<BoardLocation, BoardLocation> loc = new Pair<BoardLocation, BoardLocation>( this.getLocation(), l );
if(!this.getPlayer().getMoves().Contains( loc )) {
this.getPlayer().addMove( loc );
}
我使用的是我創建的“對”類型,但是,我試圖在C#中使用包含功能來比較這兩種類型,但是,我在“對”類型本身中使用了覆蓋功能來比較“ ToString”比較兩個對對象的()。 因此,有4個字符串被比較。 兩個鍵和兩個值。 如果兩個鍵相等,則比較兩個值。 之所以說這是合理的原因,是因為密鑰是被攻擊位置(值)的始發(密鑰)位置。 如果鍵和值相同,則不應添加對象。
public override bool Equals( object obj ) {
Pair<K, V> objNode = (Pair<K, V>)obj;
if(this.value.ToString().CompareTo( objNode.value.ToString() ) == 0) {
if(this.key.ToString().CompareTo( objNode.key.ToString() ) == 0) {
return true;
} else
return false;
} else {
return false;
}
}
問題是,是否有更好的方法來執行此操作,而不會涉及愚蠢的代碼量或創建用於處理此問題的新對象。 當然,如果有任何想法涉及到這些,我會非常高興。 令我感到困惑的部分是,也許我不了解發生了什么,但是我希望C#提供的方法只是值的等效,而不是對象內存位置等。
我也剛剛從Java移植了它,並且它的工作原理完全相同,但是我問這個問題是關於C#的問題,因為我希望有一種更好的方法來比較這些對象,而無需將ToString()與泛型一起使用類型。
您絕對可以通過使用&&
並返回相等比較的值,而不是所有if
語句和return true;
使此代碼簡單得多return true;
或return false;
陳述。
public override bool Equals (object obj) {
// Safety first: handle the case where the other object isn't
// of the same type, or obj is null. In both cases we should
// return false, rather than throwing an exception
Pair<K, V> otherPair = objNode as Pair<K, V>;
if (otherPair == null) {
return false;
}
return key.ToString() == otherPair.key.ToString() &&
value.ToString() == otherPair.value.ToString();
}
在Java中,您可以使用equals
而不是compareTo
。
請注意,這些與==
(和Equals
)使用序數比較而不是對文化敏感的比較並不完全相同 -但我懷疑這仍然是您想要的。
我個人會回避通過ToString()
表示比較值。 我將使用鍵和值類型的自然相等比較:
public override bool Equals (object obj) {
// Safety first: handle the case where the other object isn't
// of the same type, or obj is null. In both cases we should
// return false, rather than throwing an exception
Pair<K, V> otherPair = objNode as Pair<K, V>;
if (otherPair == null) {
return false;
}
return EqualityComparer<K>.Default.Equals(key, otherPair.key) &&
EqualityComparer<K>.Default.Equals(value, otherPair.value);
}
(正如Avner所述,您當然可以只使用Tuple
...)
如評論中所述,我也強烈建議您開始使用屬性和C#命名約定,例如:
if (!Player.Moves.Contains(loc)) {
Player.AddMove(loc);
}
改善此問題的最簡單方法是使用內置的Tuple<T1,T2>
類的實例代替您的自定義Pair
類。
Tuple類除了為您提供將多個值捆綁在一起的簡便方法之外,還自動實現結構相等,這意味着在以下情況下, Tuple
對象與另一個對象相等:
它是一個元組對象。
它的兩個組件與當前實例具有相同的類型。
它的兩個分量等於當前實例的兩個分量。 平等由每個組件的默認對象平等比較器確定。
( 來自MSDN )
這意味着您不必將Pair
值進行比較,而是將責任委托給Tuple
的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.