为什么不能从Value查到Key值呢? using System; using System.Collections.Generic; using System.Text; using System.Collections;
namespace _7 { class Program { static void Main(string[] args) { Hashtable hashtable = new Hashtable(); //实例化Hashtable对象 hashtable.Clear(); hashtable.Add("id", "BH0001"); //向Hashtable哈希表中添加元素 hashtable.Add("name", "TM"); hashtable.Add("sex", "Man"); Console.WriteLine(hashtable.ContainsValue("BH0001"));//判断Hashtable哈希表中是否包含指定的键值 Console.WriteLine(hashtable.ContainsKey("id")); //判断Hashtable哈希表中是否包含指定的键值
Console.WriteLine(); foreach (DictionaryEntry de in hashtable) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); }
// To get the values alone, use the Values property. ICollection valueColl = hashtable.Values;
// The elements of the ValueCollection are strongly typed // with the type that was specified for hash table values. Console.WriteLine(); foreach (string s in valueColl) { Console.WriteLine("Value = {0}", s); }
// To get the keys alone, use the Keys property. ICollection keyColl = hashtable.Keys;
// The elements of the KeyCollection are strongly typed // with the type that was specified for hash table keys. Console.WriteLine(); foreach (string s in keyColl) { Console.WriteLine("Key = {0}", s); }
// The Item property is the default property, so you // can omit its name when accessing elements. Console.WriteLine("For key = \"id\", value = {0}.", hashtable["id"]); //this is correct! it can get corresponding Value from Key! Console.WriteLine("For value = \"TM\", key = {0}.", hashtable["TM"]); //why can't get the correct result! from Value obtain its corresponding Key
} } }
哈希表从Key可以查到Value! Console.WriteLine("For key = \"id\", value = {0}.", hashtable["id"]); OK! 为什么不能从Value查到Key值呢? Console.WriteLine("For value = \"TM\", key = {0}.", hashtable["TM"]); key没有返回值!