2011-04-18 73 views
0

我不知道什麼是與此代碼的問題..它說不能將字符串轉換爲對象..類似的東西..C#的Hashtable問題

//lvLogs <-- ListView (2 colums)  

Hashtable serverLogs = new Hashtable(); 

     serverLogs.Add("a", "aw"); 
     serverLogs.Add("b", "ew"); 
     serverLogs.Add("c", "iw"); 

     foreach (DictionaryEntry h in serverLogs) 
     { 
      lvLogs.Items.Add(h.Key).SubItems.Add(h.Value);     
     }  

但是這個代碼工作正常..

Hashtable serverLogs = new Hashtable(); 

     serverLogs.Add("a", "aw"); 
     serverLogs.Add("b", "ew"); 
     serverLogs.Add("c", "iw"); 

     foreach (DictionaryEntry h in serverLogs) 
     { 
      //lvLogs.Items.Add(h.Key).SubItems.Add(h.Value); 
      //lvi.SubItems.Add(h.Value); 
      lvLogs.Items.Add(h.Key + " - " + h.Value); 
     }  

我怎樣才能從lvLogs中的列中分離鍵和值?

+0

使用Key.ToString()和Value.ToString()。但字典<字符串,字符串>是更好的,因爲別人建議 – 2011-04-18 10:27:17

回答

8

Hashtable不是強類型集合。 DictionaryEntry.Key返回一個object,並且您嘗試將其用作string而不進行強制轉換,這是不允許的。

字符串連接工作的原因是確實接受object作爲參數(它調用ToString()就可以了)。

嘗試使用Dictionary<string, string>代替。

+0

請注意,「h.Key +」 - 「+ h.Value」操作隱式地將h.Key和h.Value對象轉換爲字符串。 – Artemix 2011-04-18 11:15:06

+0

字符串concat操作'+'被編譯爲調用'String.Concat'的各種重載,它在'object'參數上調用'ToString()'。 – thecoop 2011-04-18 12:39:25

4

業務的第一個訂單,請刪除HashtableSystem.Collections命名空間中的類已過時,並且已被替換爲System.Collections.Generic命名空間中的等效項。

改爲使用Dictionary<string, string>