修改字典中的结构值

时间:2013-05-22 15:25:02

标签: c# winforms dictionary

我创建了一个字典,它接受我的struct的值并存储它们。填写此内容如下:

_screenEntry.type = typeof(string);
_screenEntry.value = tagTextBox.Text;
_screen.nodeDictionary.Add("Tag ", _screenEntry);

我的结构看起来像这样参考:

public struct Entry
{
    public Object value;
    public Type type;
}

但是,我现在正在尝试修改我第一次存储的值。我只是再次尝试重新调用nodeDictionary.Add,希望它会覆盖我以前的条目。但是,我收到一个错误,说我的字典已经有一个名为“Tag”的密钥,这是一个自我解释。

快速谷歌搜索引导我发现,如果我想覆盖我的初始值,我只需要调用此行:

_screenTag = tagTextBox.Text;    
_screen.nodeDictionary["Tag "] = _screenTag;

但是我收到以下错误:

  

错误2无法将类型'string'隐式转换为'InMoTool.Entry'

我真的不知道如何转换它。有人可能会指出方向吗?

1 个答案:

答案 0 :(得分:5)

使用此代码

_screenTag = tagTextBox.Text; // <-- is a string   
_screen.nodeDictionary["Tag "] = _screenTag;

您正尝试将string分配给Entry。那是不可能的。

我认为你需要的是这样的:

 _screenTag = tagTextBox.Text;    
 _screen.nodeDictionary["Tag "] = new Entry {
                                        type=_screenTag.GetType(), 
                                        value=_screenTag
                                      };