2013-12-09 99 views
2

所以,我想弄清楚,如何確定我的變量是否改變,增加它的價值,或減少它。我知道我可以使用一個變量來存儲舊值,但在這種情況下它不是一個選項。如何確定是一個變量增加或減少/檢測動態變化

int variable = 0; 
variable = 1; 
if(variable has increased) { 
     //Do Magic stuff 
} 

這很基本,我會怎麼想。我不知道這樣做是否有可能,沒有一箇舊的容器,但我認爲可能有一個C#函數,這可能是從一個內存地址?

我還沒有得到任何線索,這種方法或技術被稱爲是,所以對此表示贊同也會很棒。

+0

http://stackoverflow.com/questions/5842339/how-to-trigger-event-when-a-variables-value-is-changed是一個類似的題。它應該有你需要的。 – damienc88

+0

我認爲你正在尋找的'方法或技術'被稱爲[狀態機](http://stackoverflow.com/questions/5923767/simple-state-machine-example-in-c)。 – paqogomez

回答

5

使變量成爲一個屬性(在一個類中)。

在該屬性的setter中,記錄每次設置變量是增加還是減少。

例如:

class Class1 
{ 
    private int _counter; 
    private int _counterDirection; 

    public int Counter 
    { 
     get { return _counter; } 

     set 
     { 
      if (value > _counter) 
      { 
       _counterDirection = 1; 
      } 
      else if (value > _counter) 
      { 
       _counterDirection = -1; 
      } 
      else 
      { 
       _counterDirection = 0; 
      } 
      _counter = value; 
     } 
    } 

    public int CounterDirection() 
    { 
     return _counterDirection; 
    } 
} 
2
class Program 
    { 
    private int _variableValue; 
    private bool _isIncreasing; 

    public int Variable 
    { 
     get 
     { 
      return _variableValue; 
     } 
     set 
     { 
      _isIncreasing = _variableValue <= value; 
      _variableValue = value; 
     } 
    } 

    void Main(string[] args) 
    { 

     Variable = 0; 
     Variable = 1; 
     if (_isIncreasing) 
     { 
      //Do Magic stuff 
     } 
    } 
} 
相關問題