3

AクラスとBクラスの2クラスあります。

B を A ( ) に注入しDependency Injectionます。

ここで、クラス B のプロパティがいつ変更されたかを理解したいと思います。

原則とパターンに違反することなくそれを行うためのベストプラクティスは何ですか?

使いましょEventHandlersうか?

4

2 に答える 2

3

最も一般的な方法は、INotifyPropertyChanged インターフェイスを実装することです。

このインターフェイスは、次の 1 つのメンバーを定義します。

event PropertyChangedEventHandler PropertyChanged

次のように使用します。

if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

.Net 4.5 を使用する場合は、CallerMemberNameAttributeを使用できるため、手動で (または他の方法で) プロパティの名前を指定する必要はありません。

// This method is called by the Set accessor of each property. 
// The CallerMemberName attribute that is applied to the optional propertyName 
// parameter causes the property name of the caller to be substituted as an argument. 
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

上記のコードのソースは、私がリンクしたドキュメントです。

.Net 4.0 以前を使用している場合は、文字列を手動で入力する代わりに、厳密に型指定されたプロパティ名を引き続き使用できますが、このようなメソッドを実装する必要があり、式を使用して呼び出すことができます。

OnPropertyChanged(() => this.SomeProperty);
于 2013-06-08T17:22:01.153 に答える