문제

I've always implemented the IDataErrorInfo interface without actually wondering what this line means and how it works.

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

How does .this[string propertyName] work, and when/how does this property get called?

도움이 되었습니까?

해결책 2

this[key] is in fact an indexer, and is somewhat of a cross between a property and a method. It acts like a property since you can bind to it, but as opposed to regular properties, it receives a parameter.

Behind the scenes it's implemented as a method - get_Item(key), and if you'd want to access it via reflection you'd need to use Item for a name. For example:

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

This is also important to know when implementing INotifyPropertyChanged, in which case, "Item[]" or Binding.IndexerName should be used as a property name in order to update the UI.

다른 팁

This is explicit interface implementation of an indexer. (EDIT: The IDatatErrorInfo. part of the signature signifies the explicit interface implementation, and the .this[...] part signifies an indexer.)

It would be called whenever you have an explicitly typed IDataErrorInfo object and you use square brackets on it to retrieve/get a value while passing a string in. For example:

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

Note that since it's an explicit interface implementation, it will only be accessible when the type is known exactly as an IDataErrorInfo. If you have it typed as your subclass, it won't be accessible unless that class exposes it:

MyDataErrorInfoImpl myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"]; //compiler error!
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top