Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy hash code cho khóa chỉ định của Hashtable trong C#

Ví dụ 1

Kế thừa Hashtable để sử dụng phương thức GetHash:

using System;
using System.Collections;

public class HashCode : Hashtable {
    public static void Main(string[] args) {
        HashCode hash = new HashCode();
        hash.Add("A", "Jacob");
        hash.Add("B", "Mark");
        hash.Add("C", "Tom");
        hash.Add("D", "Nathan");
        hash.Add("E", "Tim");
        hash.Add("F", "John");
        hash.Add("G", "Gary");
        
        Console.WriteLine("Các cặp khóa và giá trị...");
        foreach(DictionaryEntry entry in hash) {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }
        
        Console.Write("HashCode cho khóa D =" + (hash.GetHash("D")) );
    }
}

Kết quả

Các cặp khóa và giá trị...
G and Gary
A and Jacob
B and Mark
C and Tom
D and Nathan
E and Tim
F and John
HashCode cho khóa D =-842352676

Ví dụ 2

Lấy hash code cho nhiều khóa:

using System;
using System.Collections;

public class HashCode : Hashtable {
    public static void Main(string[] args) {
        HashCode hash = new HashCode();
        hash.Add('1', "One");
        hash.Add('2', "Two");
        hash.Add('3', "Three");
        hash.Add('4', "Four");
        
        Console.WriteLine("Các cặp khóa và giá trị...");
        foreach(DictionaryEntry entry in hash) {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }
        
        Console.WriteLine("HashCode cho khóa 1 = " + (hash.GetHash('1')));
        Console.WriteLine("HashCode cho khóa 2 = " + (hash.GetHash('2')));
        Console.WriteLine("HashCode cho khóa 3 = " + (hash.GetHash('3')));
        Console.WriteLine("HashCode cho khóa 4 = " + (hash.GetHash('4')));
    }
}

Kết quả

Các cặp khóa và giá trị...
3 and Three
2 and Two
4 and Four
1 and One
HashCode cho khóa 1 = 3211313
HashCode cho khóa 2 = 3276850
HashCode cho khóa 3 = 3342387
HashCode cho khóa 4 = 3407924