2016-12-08 26 views
1

現在我沒有在我的程序中更新循環,我想避免有一個用於未來的靈活性,但我不確定這是否可能沒有一個。每當函數返回true時沒有更新循環會引發事件

如果我有一個布爾值,如:bool Update => a == b && c != d,是否有可能有一個函數自動調用,當這是真的。

另外,我知道我可以做這樣的事情:

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

但我想消息要發送的力矩值是真實的,而不是在更新環路檢測到它是真實的。

+1

您可以檢查'Update'並在由'a','b','c'和'd'的setters調用的函數中激發事件。 – Blorgbeard

+0

我也考慮過這個問題,但有一個問題是如果更新條件發生變化,我需要創建更多自定義設置器或從現有屬性中刪除自定義設置器。基本上,我期待以最乾淨的方式做到這一點。 –

回答

0

我想要一個州級班級,然後將您的活動附加到使用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中使用太多,如果需要。這樣你可以同時管理多個狀態。

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,以滿足您的要求。

相關問題