【问题标题】:Custom Dictionary read-only property自定义字典只读属性
【发布时间】:2016-09-20 08:45:39
【问题描述】:

我创建了一个自定义字典来在其上实现IDataErrorInfo 接口,但是当我尝试为此字典的实例设置值时:

自定义词典:

public class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IDataErrorInfo
{

    public string Error
    {
        get { throw new NotImplementedException(); }
    }



    public string this[string columnName]
    {
        get { throw new NotImplementedException(); }
    }
}

然后:

MyDictionary<string, string> myDict = new MyDictionary<string, string>();
    Dictionary["key"] = "value";

我收到以下错误:

无法将属性或索引器“MyDictionary.this[string]”分配给 -- 它是只读的

我想我缺少某种 Getter/Setter。但这不应该从基类 Dictionary 继承吗?如何创建它?

【问题讨论】:

标签: c# dictionary


【解决方案1】:

您的问题是,IDataErrorInfo 也实现了 this[string] 索引器。

public string this[string columnName]
{
    get { ...; }
}

如果你想访问Dictionary的索引器,你需要将你的变量强制转换为Dictionary(继承的问题之一)

((Dictionary<string,string>)variableName)["key"] = "something";

甚至更好(因为您可能永远不会手动使用IDataErrorInfo),显式实现接口:

string IDataErrorInfo.this[string columnName]
{
    get { return ...; }
}

这样您就可以像往常一样使用Dictionary 和IDataErrorInfo 索引器

dictionaryVariable["key"] = "something";
string error = ((IDataErrorInfo)dictionaryVariable)["key"];

【讨论】:

    【解决方案2】:

    Dictionary 有一个名为 Add 的方法,您应该使用它来添加到字典中。您还可以使用 .Contains 来确保该键尚未在字典中使用。

    【讨论】:

    • 但是由于我是从已经实现此方法的类“字典”扩展而来,我的自定义类不应该继承它吗?
    • 是的。我误读了这个问题。 Manfred Radlwimmer 给出了正确答案。
    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2011-12-07
    • 1970-01-01
    相关资源
    最近更新 更多