2015-03-30 80 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