2017-03-07 93 views
1

我將此VB.NET代碼轉換爲C#。字典(字符串,字符串)項目屬性C#中缺失

Dim dict As New Dictionary(Of String, String) 

If dict.TryGetValue(key, val) Then 
    dict.Item(key) = val & "~" & row.Item(y).ToString 
Else 
    dict.Add(key, row.Item(y).ToString) 
End If 

這裏是C#代碼。注意If dict.TryGetValue之後的行。智能感知不會在C#中顯示Item屬性。 C#的正確語法是什麼?

Dictionary<string, string> dict = new Dictionary<string, string>(); 

if (dict.TryGetValue(key, out val)) { 
    dict.Item[key] = val + "~" + row.ItemArray[y].ToString(); 
} else { 
    dict.Add(key, row.ItemArray[y].ToString()); 
} 
+2

'字典[關鍵]'見 - 無屬性 –

+1

'項目[關鍵]'不正確。字典中的'[]'是索引器,使用它們的正確方法是'dict [key]'。 – dcg

+3

VB.NET語法也*錯誤,或者至少是完全意外的。調用索引器屬性的正確方法是'dict(key)'。 –

回答

3

訪問在C#中的字典中鍵的值的方法如下:

dict[key] 

話雖這麼說,這條線:

dict.Item[key] = val + "~" + row.ItemArray[y].ToString(); 

應該改變像如下:

dict[key] = val + "~" + row.ItemArray[y].ToString(); 
+0

克里斯托斯 - 謝謝你的回答 - 它工作的很棒! – MisterT

+0

@MisterT不客氣!我很高興我幫助:) – Christos

3

dict.Item[key]應該是dict[key]。您正在訪問Indexer,這些可以直接從定義它們的實例訪問。

Indexers (c#)