2016-05-20 36 views
1

这很奇怪..我使用哈希表,当我尝试访问带有变量的元素时,它找不到它。c#在哈希表中使用变量时找不到对象

这里是我的代码:

namespace gramerTest 
{ 
    class Program 
    { 
     private static Hashtable byteintmap = new Hashtable(); 

     static Program() 
     { 
      Console.WriteLine("init"); 
      byteintmap.Add(0x1, 0); 
      byteintmap.Add(0x2, 1); 
      byteintmap.Add(0x3, 2); 
      byteintmap.Add(0x4, 3); 
      byteintmap.Add(0x5, 4); 
      byteintmap.Add(0x6, 5); 
     } 

     static void Main(string[] args) 
     { 
      byte b = 0x5; 
      Console.WriteLine(byteintmap[0x5] + " dir"); 
      switch (b) 
      { 
       case 0x5: 
       Console.WriteLine(byteintmap[0x5] + " s var"); 
       break; 
      } 

      Console.WriteLine(byteintmap[b]+" var"); 
     } 
    } 
} 

结果是:

 
init 
4 dir 
4 s var 
var 

回答

3

,它的发生是因为Hashtable使用对象作为其键:盒装字节不等于盒装整数(即使它们存储内部相同的值)。

您可以测试:

object a = (byte)0x5; 
object b = (int)0x5; 
Console.WriteLine(a.Equals(b)); //prints False 

你有两个选择:

  1. 将其更改为Console.WriteLine(byteintmap[(int)b]+" var");末。

  2. 使用类型化的,而不是Dictionary<int, int>