2015-03-30 74 views
-2

我有Dictionary包含字符串作为键和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!"); 
} 

调试控制台

enter image description here

键和值是类的一个对象

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

可变年底是一个整数,无关这个问题。

enter image description here

+2

有没有 '身份证' 后的空间? – zmbq 2015-03-30 19:22:30

+1

请提供一个完整的示例。 – 2015-03-30 19:26:29

+1

更改你的if语句为:if(test.ContainsKey((string)KEY.obj)),所以我们可以肯定。 – 2015-03-30 19:26:32

回答

1

您有越来越转换成您的字符串中的字节数组两个空字节。它们不会显示在字符串表示中,但它们是不同的字符串。

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 
+0

谢谢你的回答。我通过套接字发送这些字节,所以,据我所知,我必须保持2个字节的每个字符进行适当的解包,而不管第二个字节是否为0 - 不需要。因为其他字符可能包含两者。你能评论这个吗? – Scavs 2015-03-31 20:57:19

+0

如果您将它们发送给自己,那么请选择填充方案,并在收到它们时取消字节。 – 2015-03-31 21:12:55

+0

我在Java中制作服务器,并从c#客户端接收/发送数据。因为我还不得不处理endians,所以我最终没有使用Encoding类,并创建了我自己的直接转换为正确的字节的字节,而不是使用Array.reverse()进行翻转。不幸的是,我不能投票答复,接受答案就是我所能做的。 – Scavs 2015-03-31 21:21:29