C# : Creating Events for a Class on GET/SET proper

2019-06-05 23:02发布

I'm looking to fire an event each time a property within my class is SET. I'd like to be able to trigger this same event whenever one of my properties are set. I have (around 12 of them)

I.e.

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! 
}

I'm not new to events themselves, but rather new to creating events. I've always used the 'out of the box' events that are used in windows apps. Any ideas?

2条回答
成全新的幸福
2楼-- · 2019-06-05 23:40

Using INotifyPropertyChange is the right approach (because it is a widely used type in .NET, so anybody can understand what your intent is). However, if you just want some simple code to start with, then the implementation of your class might look like this:

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
} 

This is the most straightforward way to write the code (which may be good for learning and bad for larger real-world applications).

查看更多
小情绪 Triste *
3楼-- · 2019-06-05 23:45

You should implement INotifyPropertyChanged on your class to achieve this. Here's an example.

查看更多
登录 后发表回答