简体   繁体   中英

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

This is strange.. I am using a hashtable, and when I try to access an element with a variable, it does not find it.

Here is my code:

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");
        }
    }
}  

The result is:

init
4 dir
4 s var
 var

It's happening because Hashtable uses objects as keys: a boxed byte does not equal a boxed integer (even if they store the same value internally).

You can test this:

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

You have two options:

  1. Change it to Console.WriteLine(byteintmap[(int)b]+" var"); at the end.

  2. Use a typed Dictionary<int, int> instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM