在没有更新循环的情况下函数返回true时引发事件

时间:2016-12-08 02:17:55

标签: c# events delegates

现在我的程序中没有更新循环,我希望避免使用未来的灵活性,但我不确定如果没有它可以实现。

如果我有一个类似于bool Update => a == b && c != d的布尔值,那么当它为真时,是否可以自动调用函数。

或者,我知道我可以这样做:

CheckUpdate() 
{ 
   if(Update) 
       *do something here* 
}

但是我希望当前值为true时发送的消息,而不是当更新循环检测到它为真时。

2 个答案:

答案 0 :(得分:0)

我会有一个State类,然后您将事件附加到使用INotifyPropertyChanged

public class State: INotifyPropertyChanged
{
    private string a;
    private string b;
    private string c;
    private string d;

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string A
    {
        get { return this.a; }
        set
        {
            if (value != this.a)
            {
                this.a= value;
                NotifyPropertyChanged();
            }
        }
    }

    ... so on and so forth ...
}

现在你所要做的就是为属性更改分配一个处理程序......

var myState = new State();
myState += (sender,args) => 
{
    if( myState.A == myState.B && myState.C != myState.D)
    {
        // do stuff
    }
};

我使用界面的原因是,如果需要,该对象也可以在ObservableCollection中使用。这样您就可以同时管理多个状态。

答案 1 :(得分:0)

尝试这样的事情:

public class Foo
{
    public Foo()
    {
        _update = () => a == b && c != d;
    }

    private Func<bool> _update;

    private string a;
    private string b;
    private string c;
    private string d;
    private string e;
    private string f;
    private string g;
    private string h;

    private void CheckUpdate()
    {
        if (_update())
        {
            /*do something here*/
        }
    }

    public string A { get { return a; } set { a = value; CheckUpdate(); } }
    public string B { get { return b; } set { b = value; CheckUpdate(); } }
    public string C { get { return c; } set { c = value; CheckUpdate(); } }
    public string D { get { return d; } set { d = value; CheckUpdate(); } }
    public string E { get { return e; } set { e = value; CheckUpdate(); } }
    public string F { get { return f; } set { f = value; CheckUpdate(); } }
    public string G { get { return g; } set { g = value; CheckUpdate(); } }
    public string H { get { return h; } set { h = value; CheckUpdate(); } }
}

在每次更新时,只需调用CheckUpdate()就可以了多少属性。然后,您可以随时,编译时或运行时更改_update,以满足您的要求。