第一種方法
您必須覆蓋的XX
兩種方法:
Equals
,它會告訴字典中的兩個實例是否相等
GetHashCode
,它必須返回相同數量如果兩個實例相等。請注意,如果兩個實例不相同,它可以返回相同的數字,但您應該儘可能使其唯一。
您還可以實現IEquatable<XX>
在XX
類,它將mkae它明文規定XX
可以比較平等。
class XX : IEquatable<XX>
{
int t1;
char t2;
public override bool Equals(object other)
{
return Equals(other as XX);
}
public bool Equals(XX other)
{
return other != null
&& t1 == other.t1
&& t2 == other.t2;
}
public override int GetHashCode()
{
return t1^(397 * t2.GetHashCode());
}
}
方法二
創建一個實現IEqualityComparer<XX>
一類,並把它傳遞給字典的構造。您將不得不實施相同的兩種方法,但邏輯將與XX
分開,您將能夠創建具有不同鍵控方案的不同字典。
class XXEqualityComparer : IEqualityComparer<XX>
{
public static readonly XXEqualityComparer Instance = new XXEqualityComparer();
private XXEqualityComparer()
{
}
public bool Equals(XX x, XX y)
{
if (ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
return x.t1 == y.t1
&& x.t2 == y.t2;
}
public int GetHashCode(XX obj)
{
return obj == null ? 0 : obj.t1^(397 * obj.t2.GetHashCode());
}
}
然後:
var myDictionary = new Dictionary<XX, YY>(XXEqualityComparer.Instance);
第三方法
更換字典用KeyedCollection<XX, string>
。您將不得不重寫GetKeyForItem
方法爲項目提供密鑰。
class XXKeyedCollection : KeyedCollection<XX, string>
{
protected override string GetKeyForItem(XX item)
{
return string.Format("{0}{1}", t1, t2);
}
}
重要提示
請注意,爲了有一個工作辭典鍵,對象,而它的作爲字典的鍵不能改變。更確切地說,任何影響Equals
或GetHashCode
結果的字段/屬性都不得改變。
不同的實例可以具有相同的哈希碼。在這種情況下,'Equals'方法確定相等。這就是爲什麼你總是必須重寫**'Equals'和'GetHashCode'在一起。 –