IEqualityComparer.GetHashCode(Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
傳回指定物件的雜湊碼。
public:
int GetHashCode(System::Object ^ obj);
public int GetHashCode (object obj);
abstract member GetHashCode : obj -> int
Public Function GetHashCode (obj As Object) As Integer
參數
傳回
指定物件的雜湊碼。
例外狀況
obj
的型別是參考型別,而 obj
為 null
。
範例
下列程式代碼範例示範不區分大小寫 IEqualityComparer的實作。 在此範例中,方法會 GetHashCode 傳回 型別所提供的 Object 哈希碼。
ref class myCultureComparer : IEqualityComparer
{
private:
CaseInsensitiveComparer^ myComparer;
public:
myCultureComparer()
{
myComparer = CaseInsensitiveComparer::DefaultInvariant;
}
myCultureComparer(CultureInfo^ myCulture)
{
myComparer = gcnew CaseInsensitiveComparer(myCulture);
}
virtual bool Equals(Object^ x, Object^ y)
{
if (myComparer->Compare(x, y) == 0)
{
return true;
}
else
{
return false;
}
}
virtual int GetHashCode(Object^ obj)
{
return obj->ToString()->ToLower()->GetHashCode();
}
};
class myCultureComparer : IEqualityComparer
{
public CaseInsensitiveComparer myComparer;
public myCultureComparer()
{
myComparer = CaseInsensitiveComparer.DefaultInvariant;
}
public myCultureComparer(CultureInfo myCulture)
{
myComparer = new CaseInsensitiveComparer(myCulture);
}
public new bool Equals(object x, object y)
{
return myComparer.Compare(x, y) == 0;
}
public int GetHashCode(object obj)
{
return obj.ToString().ToLower().GetHashCode();
}
}
Public Class myCultureComparer
Implements IEqualityComparer
Dim myComparer As CaseInsensitiveComparer
Public Sub New()
myComparer = CaseInsensitiveComparer.DefaultInvariant
End Sub
Public Sub New(ByVal myCulture As CultureInfo)
myComparer = New CaseInsensitiveComparer(myCulture)
End Sub
Public Function Equals1(ByVal x As Object, ByVal y As Object) _
As Boolean Implements IEqualityComparer.Equals
Return myComparer.Compare(x, y) = 0
End Function
Public Function GetHashCode1(ByVal obj As Object) _
As Integer Implements IEqualityComparer.GetHashCode
Return obj.ToString().ToLower().GetHashCode()
End Function
End Class
備註
實作這個方法,為物件提供自定義哈希碼,對應至 方法所提供的 Equals 自定義相等比較。
給實施者的注意事項
實作必須確定如果 Equals(Object, Object) 方法針對兩個 對象x
和 傳y
回 true
,則的方法x
所傳回的值必須等於 傳GetHashCode(Object)回的值y
。