Use byte[] as key in dictionary

前端 未结 7 1599
南旧
南旧 2020-12-28 12:11

I need to use a byte[] as a key in a Dictionary. Since byte[] doesn\'t override the default GetHashCode method, two sepa

7条回答
  •  旧巷少年郎
    2020-12-28 12:45

    When you are retrieving the items from the Dictionary you are using new operator for the byte[]. This will look for a different (new) byte[] instance in the Dictionary which is not present.

    Here is a solution that will work:

     var dict = new Dictionary();
    
                var b = new byte[] { 1,2,3};
    
                dict[b] = "my string";
    
                var value = dict[b]; 
    
                Console.WriteLine(value);
    

提交回复
热议问题