IEqualityComparer.GetHashCode(Object) 方法

定義

傳回指定物件的雜湊碼。

C#
public int GetHashCode (object obj);

參數

obj
Object

要傳回雜湊碼的 Object

傳回

指定物件的雜湊碼。

例外狀況

obj 的型別是參考型別,而 objnull

範例

下列程式代碼範例示範不區分大小寫 IEqualityComparer的實作。 在此範例中,方法會 GetHashCode 傳回 型別所提供的 Object 哈希碼。

C#
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();
    }
}

備註

實作這個方法,為物件提供自定義哈希碼,對應至 方法所提供的 Equals 自定義相等比較。

給實施者的注意事項

實作必須確定如果 Equals(Object, Object) 方法針對兩個 對象x和 傳ytrue ,則的方法x所傳回的值必須等於 傳GetHashCode(Object)回的值y

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱