C#:在GET / SET属性上为类创建事件

我希望每次我的class级中的一个房产都被设置时发射一个事件。 我希望能够在设置我的某个属性时触发同一事件。 我有(大约12个)

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应用程序中使用的“开箱即用”事件。 有任何想法吗?

使用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 } 

这是编写代码最直接的方式(这可能对学习有好处,对于更大的实际应用程序则有害)。

您应该在类上实现INotifyPropertyChanged来实现此目的。 这是一个例子 。