日期:2014-05-18  浏览次数:20755 次

为什么不能从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没有返回值!

------解决方案--------------------
探讨

引用:

key是唯一不能重复,value可以重复,key与value的关系是1对多


没问题! 一对几! 一对多等等!
我的问题是: 是否不能从Value!查找Key! 这是否哈希表的硬性规定!因为我从来没有看到这个规定!
而只是其他人的示例->怎么怎么做而已!