Mục đích
Phương thức Hashtable.Contains(object key) (hoặc ContainsKey) kiểm tra xem key có tồn tại trong Hashtable hay không. Trả về true/false.
Ví dụ 1: Hashtable với nhiều entry
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
Hashtable hash = new Hashtable();
hash.Add("One", "Katie");
hash.Add("Two", "John");
hash.Add("Three", "Barry");
hash.Add("Four", ""); // Empty string
hash.Add("Five", "Harry");
hash.Add("Six", "F");
hash.Add("Seven", "Tom");
hash.Add("Eight", "Andy");
hash.Add("Nine", "I");
hash.Add("Ten", "Tim");
Console.WriteLine("Hashtable Key/Value:");
foreach (DictionaryEntry entry in hash)
Console.WriteLine($"{entry.Key} and {entry.Value}");
Console.WriteLine($"\nIsFixedSize: {hash.IsFixedSize}");
Console.WriteLine($"IsReadOnly: {hash.IsReadOnly}");
Hashtable syncHash = Hashtable.Synchronized(hash);
Console.WriteLine($"IsSynchronized (sync wrapper): {syncHash.IsSynchronized}");
Console.WriteLine($"\nContains key 'Ten': {hash.Contains("Ten")}"); // True
Console.WriteLine($"Contains key 'Eleven': {hash.Contains("Eleven")}"); // False
}
}
Kết quả
Hashtable Key/Value:
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and
Eight and Andy
Nine and I
Six and F
IsFixedSize: False
IsReadOnly: False
IsSynchronized (sync wrapper): True
Contains key 'Ten': True
Contains key 'Eleven': False
Ví dụ 2: Truy xuất giá trị và kiểm tra key không tồn tại
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
Hashtable hash = new Hashtable();
hash.Add("1", "AB"); hash.Add("2", "BC"); hash.Add("3", "DE");
hash.Add("4", "EF"); hash.Add("5", "GH"); hash.Add("6", "IJ");
hash.Add("7", "KL"); hash.Add("8", "MN"); hash.Add("9", "OP");
hash.Add("10", "QR");
Console.WriteLine($"Value at key '3': {hash["3"]}"); // DE
Console.WriteLine($"Contains key '12': {hash.Contains("12")}"); // False
}
}
Kết quả
Value at key '3': DE
Contains key '12': False
Contains vs ContainsKey vs indexer
| Phương thức | Mô tả | Trả về |
|---|---|---|
Contains(key) | Kiểm tra key tồn tại (legacy) | bool |
ContainsKey(key) | Tương tự, tên rõ nghĩa hơn (IDictionary) | bool |
ContainsValue(value) | Kiểm tra value tồn tại (O(n)) | bool |
hash[key] | Lấy value, ném KeyNotFoundException nếu thiếu | object (value) |
Lưu ý
Hashtable**case-sensitive** cho key string (khác StringDictionary).- Key không được null. Value có thể null.
- Thread-safe: dùng
Hashtable.Synchronized()wrapper (như ví dụ). - **Legacy**: Khuyến nghị dùng
Dictionary<TKey, TValue>(generic, nhanh hơn, type-safe). - Hashtable dùng
GetHashCodevàEqualscủa key.