2013-04-15 1 views
7

特定のクラスで何かが変化したときに何らかのイベントをトリガーすることはできますか?クラス内で何かが変化したときにイベントをトリガーします

など。私は100のフィールドを持つクラスを持っており、そのうちの1つは外部的にまたは内部的に変更されています。今私はこのイベントをキャッチしたい。これを行う方法?

本当に拡張されたクラスのためにこれをすばやく行うためのトリックがあるかどうかは分かりません。

+0

これはデバッグ用ですか、UIの更新用ですか?それに応じて答えは異なります。 –

+0

UIを更新して他の多くのことを行っている – Nickon

答えて

13

ベストプラクティスとして、手動プロパティにパブリックフィールドを変換し、実装して変更eventを上げるためにINotifyPropertyChangedinterfaceclass

EDIT:あなたは100個のフィールドを述べたので、私はこの偉大な答えのようにあなたのコードをリファクタリングするあなたを示唆している:ここでTools for refactoring C# public fields into properties

はその一例です:

private string _customerNameValue = String.Empty; 
public string CustomerName 
{ 
    get 
    { 
     return this._customerNameValue; 
    } 

    set 
    { 
     if (value != this._customerNameValue) 
     { 
      this._customerNameValue = value; 
      NotifyPropertyChanged(); 
     } 
    } 
} 
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 
{ 
    if (PropertyChanged != null) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

はこれをチェックしてください: INotifyPropertyChanged Interface

+0

私はこれを恐れて、手動で各フィールドを変更する必要があります:S – Nickon

+2

Rafactor your code!それは簡単です:[C#パブリックフィールドをプロパティにリファクタリングするためのツール](http://stackoverflow.com/questions/1028679/tools-for-refactoring-c-sharp-public-fields-into-properties) –

+1

[この質問]へのすべての回答(http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist)。 – TylerOhlsen

関連する問題