如何为我的类创建事件处理程序

Pra*_*dda 0 .net c#

我有下课

public class ButtonChange
{
   private int _buttonState;
   public void  SetButtonState(int state)
   {
            _buttonState = state;
   }
}
Run Code Online (Sandbox Code Playgroud)

我想在_buttonState值发生变化时触发一个事件,最后我想在中定义一个事件处理程序ButtonChange

你们能帮我吗?

PS:我不想使用INotifyPropertyChanged

Jon*_*eet 7

怎么样:

public class ButtonChange
{
   // Starting off with an empty handler avoids pesky null checks
   public event EventHandler StateChanged = delegate {};

   private int _buttonState;

   // Do you really want a setter method instead of a property?
   public void SetButtonState(int state)
   {
       if (_buttonState == state)
       {
           return;
       }
       _buttonState = state;
       StateChanged(this, EventArgs.Empty);
   }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望StateChanged事件处理程序知道新状态,您可以从中派生自己的类EventArgs,例如ButtonStateEventArgs然后使用事件类型EventHandler<ButtonStateEventArgs>.

请注意,此实现不会尝试是线程安全的.