📜  C#|如何获取哈希表的指定键的哈希码

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

Hashtable.GetHash(Object)方法用于获取Hashtable对象的指定键的哈希码。此方法是从Object类继承的。

句法:

protected virtual int GetHash(Object Key);

异常:如果为null,则此方法将提供NullReferenceException。

下面的程序说明了上面讨论的方法的使用:

范例1:

// C# Program to illustrate the 
// Hashtable.GetHash(Object) method
using System;
using System.Collections;
  
// Inheriting Hashtable as 
// Hashtable.GetHash(Object) 
// method is protected method
class HashCode : Hashtable {
      
    // Main Method
    static void Main(string[] args)
    {
          
        // creating object for HashCode as
        // to access protected methods we
        // have to create object for the 
        // derived class
        HashCode h = new HashCode();
          
        // Add Elements into Hashtable
        h.Add("1001", "Parek Shetty");
        h.Add("1002", "Deshmuk Narayan");
        h.Add("1003", "Ratan Kaalikaran");
          
        ICollection Key = h.Keys;
  
        foreach(string val in Key)
        {
              
            // printing Hashtable
            Console.Write(val + " : " + h[val]);
            Console.Write("\n");
              
            // printing hashcode with keys
            int hcode = h.GetHash(val);
              
            Console.Write(val + " : " + hcode);
            Console.Write("\n");
        }
    }
}
输出:
1002 : Deshmuk Narayan
1002 : 985757554
1001 : Parek Shetty
1001 : -1708895167
1003 : Ratan Kaalikaran
1003 : -1892225314

范例2:

// C# Program to illustrate the 
// Hashtable.GetHash(Object) method
using System;
using System.Collections;
  
class HashCode : Hashtable {
      
    // Main Method
    static void Main(string[] args)
    {
        HashCode h = new HashCode();
          
        // Adding elements
        h.Add('A', "Pritam Devadhya");
        h.Add('B', "Arjun Balachi");
        h.Add('C', "Timanad Panigrahi");
          
        ICollection Key = h.Keys;
          
        int hcode = h.GetHash('C');
          
        Console.Write("HashCode: " + hcode);
    }
}
输出:
HashCode: 4390979

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.gethash?view=netframework-4.7.2