2016-05-23 68 views
0

我创建了一个自定义词典来实现就可以了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"; 

我得到以下错误:

Property or indexer 'MyDictionary.this[string]' cannot be assigned to -- it is read only

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

+1

一个[MCVE]将是有益的,但 –

回答

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"]; 
0

词典有一个方法,叫你应该用它来添加到字典中。您还可以使用.Contains来确保密钥在字典中尚未使用。

+0

因为我从已有这种方法实现的类“说文解字”延伸不该”我的自定义类继承它吗? –

+0

是的。我误解了这个问题。 Manfred Radlwimmer有正确的答案。 –