2010-02-20 49 views
1

我期待每次在我的類中設置屬性時觸發一個事件。我希望能夠觸發這個相同的事件,只要我的一個屬性被設置。我有(其中大約12個)C#:爲GET/SET屬性上的類創建事件

即,

public class MyClass 
{ 
    private int _myHeight; 
    private int _myWidth; 

public int myHeight 
{ 
    get { return myHeight; } 
    set { myHeight = value; 
     //This fires event! 
     } 
} 
public int myWidth 
{ 
    get { return myWidth; } 
    set { myWidth = value; 
     //This will fire the same event! 
} 

我對事件本身並不陌生,但對創建事件來說卻是新事物。我一直使用Windows應用程序中使用的'開箱即用'事件。有任何想法嗎?

+0

看看這個問題它就是你在爲什麼http://stackoverflow.com/questions/2264533/listener-c-like-java/2264547#2264547 – IordanTanev 2010-02-20 16:33:00

回答

3

使用INotifyPropertyChange是正確的方法(因爲它是.NET中廣泛使用的類型,所以任何人都可以理解你的意圖是什麼)。但是,如果你只是想一些簡單的代碼,開始時,那麼你的類的實現可能是這樣的:

public class MyClass 
{ 
    private int _myHeight; 
    public event EventHandler Changed; 

    protected void OnChanged() { 
    if (Changed != null) Changed(this, EventArgs.Empty); 
    } 

    public int myHeight 
    { 
    get { return myHeight; } 
    set { 
     myHeight = value; 
     OnChanged(); 
    } 
    } 
    // Repeat the same pattern for all other properties 
} 

這是寫的代碼(這可能是很好的學習和壞的最直接的方法適用於更大的實際應用)。

+1

這確實是正常的做法。我還鼓勵你在設置領域和提高事件之前檢查mHeight實際上是否改變了不同的值。否則,如果UI監聽事件並設置成員,則可能會陷入無限事件級聯。 – munificent 2010-02-22 22:57:07

+0

好點 - 檢查實際改變的值是否非常有用。 – 2010-02-23 00:05:15

5

你應該在你的課上實現INotifyPropertyChanged來達到這個目的。這是一個example

+0

+1:從來不知道這個接口 – contactmatt 2010-03-08 05:48:01

+0

@ contactmatt它主要用於WPF開發。 – Esteban 2013-09-26 22:42:45