[英]Custom Dictionary read-only property
I created a custom dictionary to implement the IDataErrorInfo
interface on it, but when I try to set a value to an instance of this Dictionary: 我创建了一个自定义词典来在其上实现
IDataErrorInfo
接口,但是当我尝试为该Dictionary的实例设置值时:
Custom Dictionary: 自定义词典:
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(); }
}
}
Then: 然后:
MyDictionary<string, string> myDict = new MyDictionary<string, string>();
Dictionary["key"] = "value";
I get the following error: 我收到以下错误:
Property or indexer 'MyDictionary.this[string]' cannot be assigned to -- it is read only
属性或索引器“ MyDictionary.this [string]”无法分配给它-只读
I guess I'm missing some kind of Getter/Setter. 我想我缺少某种Getter / Setter。 But shouldn't this be inherited from base class Dictionary?
但这不应该从基类Dictionary继承吗? How can I create it?
如何创建它?
Your problem is, that IDataErrorInfo
implements the this[string]
indexer too. 您的问题是
IDataErrorInfo
实现了this[string]
索引器。
public string this[string columnName]
{
get { ...; }
}
If you want to access the indexer of Dictionary
you need to cast your variable to Dictionary
(one of the problems of inheritance) 如果要访问
Dictionary
的索引器,则需要将变量转换为Dictionary
(继承问题之一)。
((Dictionary<string,string>)variableName)["key"] = "something";
or even better (since you'll probably never use IDataErrorInfo
manually), implement the interface explicitly : 甚至更好(因为您可能永远不会手动使用
IDataErrorInfo
),请显式实现接口:
string IDataErrorInfo.this[string columnName]
{
get { return ...; }
}
That way you can use the Dictionary
like usual and the IDataErrorInfo
indexer by casting 这样,您可以像平常一样使用
Dictionary
和IDataErrorInfo
索引器,方法是强制转换
dictionaryVariable["key"] = "something";
string error = ((IDataErrorInfo)dictionaryVariable)["key"];
Dictionary has a method called Add which you should use to add to the dictionary. 字典有一个称为Add的方法,您应该使用该方法将其添加到字典中。 You can also use .Contains to ensure the key isn't already used in the dictionary.
您还可以使用.Contains来确保字典中尚未使用该键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.