布尔值为真时的事件



我正在用c#(WPF)编程。我的类中有一些Boolean变量,例如isConnectedisBusy。我想定义一个event,并为它们event handler当我的布尔变量发生变化时,我运行一个方法。

我搜索并找到了一些东西,但我无法理解它们。

你能帮我写吗?


更新 1:

最后我写了它,但我得到了StackOverFlowExeception,这可能是由递归引起的。怎么了?

    public event EventHandler IsConnectedChanged;
    public bool IsConnected
    {
        get { return IsConnected; }
        set
        {
            IsConnected = value;
            CheckAndCallHandlers();
        }
    }

    private void CheckAndCallHandlers()
    {
        EventHandler handler = IsConnectedChanged;
        if (IsConnected)
            handler(this, EventArgs.Empty);
    }

变量包装在属性中,然后在属性的 setter 中,您可以调用一个检查是否两者都true的方法。满足该条件后,您可以执行额外的工作:

public class SomeClass
{
    private bool _isConnected;
    private bool _isBusy;
    public event EventHandler SomeCustomEvent;
    public bool IsConnected
    {
        get { return _isConnected; }
        set
        {
            _isConnected = value;
            CheckAndCallHandlers();
        }
    }
    public bool IsBusy
    {
        get { return _isBusy; }
        set
        {
            _isBusy = value;
            CheckAndCallHandlers();
        }
    }
    private void CheckAndCallHandlers()
    {
        var handler = SomeCustomEvent;
        if(IsConnected && IsBusy && handler != null)
            handler(this, EventArgs.Empty);
    }
}

使其成为属性

bool _isConnected;
bool isConnected
{
  get { return _isConnected; }
  set {
    if (value != _isConnected) //it's changing!
    {
      doSomething();
    }
    _isConnected = value; //Could do this inside the if but I prefer it outside because some types care about assignment even with the same value.
  }  
}

相关内容

  • 没有找到相关文章

最新更新