要實現C#中Hashtable的自定義鍵類型,首先需要創建一個自定義的類作為鍵類型,然后重寫該類的Equals和GetHashCode方法。這樣可以確保Hashtable在查找鍵值對時能夠正確比較自定義鍵類型的實例。
下面是一個示例代碼,演示了如何實現自定義鍵類型的Hashtable:
using System;
using System.Collections;
// 自定義鍵類型
public class CustomKey
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
CustomKey other = (CustomKey)obj;
return Id == other.Id && Name == other.Name;
}
public override int GetHashCode()
{
return Id.GetHashCode() ^ Name.GetHashCode();
}
}
class Program
{
static void Main()
{
Hashtable hashtable = new Hashtable();
CustomKey key1 = new CustomKey { Id = 1, Name = "Key1" };
CustomKey key2 = new CustomKey { Id = 2, Name = "Key2" };
hashtable[key1] = "Value1";
hashtable[key2] = "Value2";
Console.WriteLine(hashtable[key1]); // 輸出 "Value1"
Console.WriteLine(hashtable[key2]); // 輸出 "Value2"
}
}
在上面的示例中,我們創建了一個名為CustomKey的自定義鍵類型,其中包含Id和Name屬性。然后重寫了Equals和GetHashCode方法,以確保鍵值對在Hashtable中的正確比較。
在Main方法中,我們創建了一個Hashtable實例,并用自定義鍵類型作為鍵,將值存儲在Hashtable中。最后,我們通過自定義鍵類型來獲取值,并輸出結果。