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

时间:2013-06-21 13:27:41

标签: c# wpf idataerrorinfo

我一直在实现IDataErrorInfo界面,而实际上并不知道这条线的含义及其工作原理。

string IDataErrorInfo.this[string propertyName]
{
    get { return this.GetValidationError(propertyName); }
}

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

2 个答案:

答案 0 :(得分:7)

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

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

IDataErrorInfo myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"];

请注意,由于它是一个显式的接口实现,因此只有当类型完全作为IDataErrorInfo时才能访问它。如果您将其键入为子类,则除非该类公开它,否则将无法访问它:

MyDataErrorInfoImpl myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"]; //compiler error!

答案 1 :(得分:2)

this[key]实际上是一个索引器,在属性和方法之间有点交叉。它就像一个属性,因为你可以绑定它,但与常规属性相反,它接收一个参数。

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

typeof(MyClass).GetProperty("Item");

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