當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Object.GetHashCode()用法及代碼示例


此方法用於返回此實例的哈希碼。哈希碼是一個數字值,用於在基於哈希的集合中插入和標識對象。的GetHashCode 方法為需要快速檢查對象相等性的算法提供此哈希代碼。

用法:

public virtual int GetHashCode ();

返回值:此方法返回當前對象的32位帶符號整數哈希碼。


以下示例程序旨在說明Object.GetHashCode()方法的使用:

示例1:

// C# program to demonstrate 
// Object.GetHashCode() Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // declaring an object 
        Object obj = new Object(); 
  
        // taking Type type and assigning 
        // the value as type of above 
        // defined types using GetType 
        // method 
        Type t = obj.GetType(); 
  
        // Display type and hash code 
        Console.WriteLine("Type is :{0}", t); 
        Console.WriteLine("Hash Code is :{0}", 
                             t.GetHashCode()); 
    } 
}
輸出:
Type is :System.Object
Hash Code is :37162120

示例2:

// C# program to demonstrate 
// Object.GetHashCode() Method 
using System; 
  
public class Author { 
  
    public string f_Name; 
    public string l_Name; 
  
    public Author(string f_Name,  
                  string l_Name) 
    { 
        this.f_Name = f_Name; 
        this.l_Name = l_Name; 
    } 
  
    public void Show() 
    { 
        Console.WriteLine("first Name : "
                               + f_Name); 
  
        Console.WriteLine("last Name : " 
                              + l_Name); 
    } 
} 
  
// Driver Class 
class GFG { 
  
    // Main method 
    public static void Main() 
    { 
  
        // Creating and initializing  
        // the object of Author class 
        Author aobj = new Author("Kirti", "Mangal"); 
  
        Console.WriteLine("Author details:"); 
        aobj.Show(); 
  
        // Get the Hash Code of aobj object 
        // Using GetHashCode() method 
        Console.WriteLine("The hash code of object is: {0}", 
                                        aobj.GetHashCode()); 
    } 
}
輸出:
Author details:
first Name : Kirti
last Name : Mangal
The hash code of object is: -751588944

重要事項:

  • 返回相等的哈希碼的兩個對象意味著對象相等,但反之則不成立。意思是,相等的哈希碼並不意味著對象相等,因為不同的(不相等)對象可以具有相同的哈希碼。
  • .NET Framework不保證GetHashCode方法的默認實現,並且此方法返回的值在.NET Framework版本和平台(例如32位和64位平台)之間可能有所不同。
  • 哈希碼不是永久值,因此請勿序列化,將哈希值存儲在數據庫中等。
  • 不要測試哈希碼是否相等,以確定兩個對象是否相等。

參考:https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.7.2



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 C# | Object.GetHashCode() Method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。