我是一名新手,目前正在将 C++ 代码翻译成 C#。我有一张 map
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
并且您拥有它的所有权,那么最好 Dispose()
它,在与 C++ 中使用的方式类似
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()
。即使在 C++ 中也是引用,他们选择 clone()
Object
有点奇怪。如果你想 clone()
它,显然你需要为你的 CloneableObject
公开一个方法来克隆它。请注意,C# 中的 Object
(或 object
)不是“开箱即用”的可克隆对象。您必须编写代码才能克隆它。
关于c# - 访问 C# 字典中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025806/