c#在哈希表中使用变量时找不到对象

c# can't find object when use variable in hashtable

这很奇怪。我正在使用哈希表,当我尝试使用变量访问元素时,它找不到它。

这是我的代码:

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

这是因为 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>