📜  C#|带示例的Object.GetHashCode()方法

📅  最后修改于: 2021-05-29 22:03:43             🧑  作者: Mango

此方法用于返回此实例的哈希码。哈希码是一个数字值,用于在基于哈希的集合中插入和标识对象。 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/zh-cn/dotnet/api/system.object.gethashcode?view=netframework-4.7.2