IDataErrorInfo.this [string propertyName]如何在C#中工作?

Rac*_*hel 5 c# wpf idataerrorinfo

我总是实现IDataErrorInfo接口,而实际上并不知道这条线的含义及其工作原理.

string IDataErrorInfo.this[string propertyName]
{
    get { return this.GetValidationError(propertyName); }
}
Run Code Online (Sandbox Code Playgroud)

如何.this[string propertyName]工作,以及何时/如何调用此属性?

Chr*_*air 7

这是显式接口实现的的索引.(编辑:IDatatErrorInfo.签名的一部分表示显式接口实现,该.this[...]部分表示索引器.)

只要你有一个显式类型的IDataErrorInfo对象,并且在它上面使用方括号来检索/获取值,同时传入一个字符串,就会调用它.例如:

IDataErrorInfo myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"];
Run Code Online (Sandbox Code Playgroud)

需要注意的是,因为它是一个显式接口实现,它只会在类型是已知的可访问正好作为IDataErrorInfo.如果您将其键入为子类,则除非该类公开它,否则将无法访问它:

MyDataErrorInfoImpl myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"]; //compiler error!
Run Code Online (Sandbox Code Playgroud)


Adi*_*ter 3

this[key]实际上是一个索引器,并且在某种程度上是属性和方法之间的交叉。它的作用就像一个属性,因为您可以绑定到它,但与常规属性相反,它接收一个参数。

在幕后,它作为方法实现 - get_Item(key),如果您想通过反射访问它,则需要使用Item名称。例如:

typeof(MyClass).GetProperty("Item");
Run Code Online (Sandbox Code Playgroud)

在实现 时了解这一点也很重要INotifyPropertyChanged,在这种情况下,应将"Item[]"Binding.IndexerName用作属性名称以更新 UI。