添加到词典不添加

Adding to Dictionary does not add

我有一个字典,其中包含字符串作为键和 System.Object 作为值。

Dictionary<string, System.Object> test = new Dictionary<string, System.Object>();

我创建并添加值

Debug.Log("Key:" + (string)KEY.obj);
Debug.Log("VALUE:" + (string)VALUE.obj);

test.Add((string)KEY.obj, VALUE.obj);

if (test.ContainsKey("id")){
    Debug.Log("contains!");
}
else{
    Debug.Log("does not contain!");
}

调试控制台

KEY 和 VALUE 是 class

的对象
private sealed class ResolveValue {

    public readonly System.Object obj;
    public readonly int end;

    public ResolveValue(System.Object obj, int end){
        this.obj = obj;
        this.end = end;
    }
}

其中 KEY 是 "id",VALUE 是 "myData"。

我花了很长时间才找到问题所在。 这怎么可能?

附加信息

所有字符串都是从字节转换而来的。 这是我进行的调试。

Debug.Log("--------");

string msg = "";
foreach(byte b in bytes){
    msg += b + " ";
}
Debug.Log(msg);

Debug.Log("--------");

string message = System.Text.Encoding.UTF8.GetString(bytes);
Debug.Log(message);

ResolveValue response = new ResolveValue(message, end);

变量end是整数,与本题无关

您的字节数组中有两个空字节正在转换为您的字符串。它们不会出现在字符串表示中,但它们是不同的字符串。

byte[] bytes= System.Text.Encoding.UTF8.GetBytes("id");
foreach (byte b in bytes)
   {Console.WriteLine(b);}

产量

105
100

同时

var b1 = new byte[]{105,100,0,0};
var b2 = new byte[]{105,100};
Console.WriteLine(System.Text.Encoding.UTF8.GetString(b1)==System.Text.Encoding.UTF8.GetString(b2));

产量

False