[英]Accessing elements in C# dictionary
我是新手,目前正在將C ++代碼翻譯為C#。 我有一張地圖
map<string, Object*> table;
和一個功能
void define(const string& symbol, Object* definition)
{
map<string, Object*>::iterator iter = table.find(symbol);//returns iterator to element with key "symbol," else sets equal to map::end
if (iter != table.end())//if key is in map
{
delete (*iter).second;
table.erase(iter);
}
table.insert(pair<string, Object*>(symbol,definition->clone()));
}
我想在C#中創建等效函數。 我創建了一個字典:
private Dictionary<string, Object> table = new Dictionary<string, Object>();
這是我到目前為止的功能
public void define(string symbol, Object definition)
{
if (table.ContainsKey(symbol))
{
//function body
}
現在需要我的功能體來完成同樣的事情。 根據我的研究,C#似乎沒有相同的迭代器結構。
最后,您的方法將替換一個元素(如果存在)或將其添加...在C#中,您可以簡單地:
public void define(string symbol, Object definition)
{
table[symbol] = definition;
}
請注意,如果definition
可以是IDisposable
且您擁有它的所有權,那么最好以類似於C ++中使用的方式將Dispose()
用作它。
public void define(string symbol, Object definition)
{
object oldDefinition;
if (table.TryGetValue(symbol, out oldDefinition) && oldDefinition != null)
{
IDisposable disp = oldDefinition as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
table[symbol] = definition;
}
對於clone()
您必須選擇如何處理clone()
。 即使是C ++中的引用,他們選擇clone()
Object
有點奇怪。 如果要clone()
,顯然需要為CloneableObject
公開一個方法來克隆它。 請注意,C#中的Object
(或object
)不可“即開即用”地克隆。 您必須編寫代碼以克隆它。
如果我理解正確,則需要在c#
字典上進行迭代。 您可以使用以下方法之一在c#
遍歷dictionary
foreach(var pair in table)
{
var key = pair.Key;
var value = pair.Value;
}
要么
foreach(KeyValuePair<string, Object> entry in table)
{
// do something with entry.Value or entry.Key
}
要么
for (int index = 0; index < table.Count; index++) {
var item = table.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
您可以在foreach
循環中添加if
子句並對其進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.