c# - 访问 C# 字典中的元素

标签 c# c++ dictionary iterator

我是一名新手,目前正在将 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/

相关文章:

c# - 在通过 EF6 上的 Code First 实现创建的 MySql 表上创建 PARTITION

c++ - 在 vector<pair<string, int>> 上使用 std::sort 的段错误

python - 将列表初始化为循环内字典中的变量

python - 使用关键字的行号创建字典

c++ - 为什么使用一个参数而不是两个参数调用释放函数?

java - 将列表映射的所有组合生成为列表列表

c# - 如何将 SQL 中的多个内部联接转换为 LINQ?

javascript - 尝试将 $UI 元素附加到 <div> 标记时,如果没有错误输出,JQuery 将无法工作

c# - Windows Azure - 辅助角色 - 检测环境

c++ - 如何在 *.exe 上启用拖动文件并将其作为参数获取?