Hashtable 클래스는 키의 해시 코드를 기반으로 구성된 키-값 쌍의 컬렉션을 나타냅니다. 컬렉션의 요소에 액세스하기 위해 키를 사용합니다.
Hashtable 클래스에서 일반적으로 사용되는 방법 중 일부는 -
| 시니어 번호 | 방법 및 설명 |
|---|---|
| 1 | 공개 가상 무효 추가(객체 키, 객체 값); 지정된 키와 값이 있는 요소를 Hashtable에 추가합니다. |
| 2 | 공개 가상 무효 Clear(); Hashtable에서 모든 요소를 제거합니다. |
| 3 | 공개 가상 bool ContainsKey(객체 키), Hashtable에 특정 키가 포함되어 있는지 여부를 결정합니다. |
| 4 | 공개 가상 bool ContainsValue(객체 값), Hashtable에 특정 값이 포함되어 있는지 여부를 결정합니다. |
다음은 C#에서 Hashtable 클래스의 사용법을 보여주는 예제입니다.
예시
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
Hashtable ht = new Hashtable();
ht.Add("D01", "Finance");
ht.Add("D02", "HR");
ht.Add("D03", "Operations");
if (ht.ContainsValue("Marketing")) {
Console.WriteLine("This department name is already in the list");
} else {
ht.Add("D04", "Marketing");
}
ICollection key = ht.Keys;
foreach (string k in key) {
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
}
}
} 위에서 Hashtable 클래스 add() 메서드를 사용하여 키와 값 쌍으로 요소를 추가했습니다.
Hashtable ht = new Hashtable();
ht.Add("D01", "Finance");
ht.Add("D02", "HR");
ht.Add("DO3", "Operations"); 출력
D04: Marketing D02: HR D03: Operations D01: Finance