Accessing elements in the C # dictionary

I am a newbie currently translating C++ code to C#. I have a map

map table;

and a function

void define(const string& symbol, Object* definition)
{
    map::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(symbol,definition->clone()));
}

and I want to create the equivalent function in C#. I’ve created a Dictionary:

private Dictionary table = new Dictionary();

and here is my function so far

public void define(string symbol, Object definition)
    {
        if (table.ContainsKey(symbol))
        {
//function body
        }

and now need my function body to accomplish the same thing. From my research, it doesn’t seem like C# has the same iterator structure.

Your method in the end replaces an element (if present), or adds it… In C# you can simply:

public void define(string symbol, Object definition)
{
    table[symbol] = definition;
}

Note that if definition
can be IDisposable
and you have ownership of it, then it would be better to Dispose()
it, in a similar manner to the one used in 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;
}

For the clone()

You have to choose how to handle the clone()
. Being references even in C++, it is a little strange that they chosed to clone()
the Object
. If you want to clone()
it, clearly you’ll need to expose a method for your CloneableObject
to clone it. Note that Object
(or object
) in C# isn’t cloneable “out of the box”. You have to write the code to clone it.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Accessing elements in the C # dictionary

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录