2014-04-01 41 views
1

我有以下方法,當我的應用程序中的手勢匹配時被調用,但計數器只在該方法內增加一次,因此每次追加匹配後,初始匹配不會增加計數器和標籤。有人可以看到,如果這是我的反邏輯邏輯中的缺陷,或者我應該以不同的方式實施計數器?遞增一個手勢匹配的分數計數器

這是我目前的解決方案只增加在第一場比賽:

void matcher_GestureMatch(Gesture gesture) 
     { 
      int scoreCntr = 0; 
      lblGestureMatch.Content = gesture.Name; 
      scoreCntr++; 

      var soundEffects = Properties.Resources.punchSound; 
      var player = new SoundPlayer(soundEffects); 
      player.Load(); 
      player.Play(); 

      lblScoreCntr.Content = scoreCntr; 

     } 
+0

它不僅在第一次匹配時增量,它總是將'scoreCntr'設置爲零,增加它,然後將該值(總是一個)賦值給'lblScoreCntr.Content'。 – 48klocs

回答

2

您重置每次運行方法時,你的計數爲0。最快的修復方法是在方法之外聲明變量:

int scoreCntr = 0; 
void matcher_GestureMatch(Gesture gesture) 
{ 
    lblGestureMatch.Content = gesture.Name; 
    scoreCntr++; 

    var soundEffects = Properties.Resources.punchSound; 
    var player = new SoundPlayer(soundEffects); 
    player.Load(); 
    player.Play(); 

    lblScoreCntr.Content = scoreCntr; 
} 
1

您需要將scoreCntr移出方法的範圍。這種方法運行時,它只是「活着」的,所以你想在它所處的類的生命週期中保持活躍。下面是一個例子:

private int scoreCntr = 0; 

    void matcher_GestureMatch(Gesture gesture) 
    { 
     lblGestureMatch.Content = gesture.Name; 
     Interlocked.Increment(ref scoreCntr); 

     var soundEffects = Properties.Resources.punchSound; 
     var player = new SoundPlayer(soundEffects); 
     player.Load(); 
     player.Play(); 

     lblScoreCntr.Content = scoreCntr; 
    }