【问题标题】:Incrementing a score counter on a gesture match在手势匹配上增加分数计数器
【发布时间】:2014-04-01 16:58:43
【问题描述】:

当手势在我的应用程序中匹配时,我有以下方法被调用,但计数器仅在该方法中增加一次,因此初始匹配后的每个额外匹配不会增加计数器和标签。有人能看出这是我的计数器逻辑中的缺陷还是我应该以不同的方式实现计数器?

这是我目前的解决方案,仅在第一场比赛时增加:

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;

        }

【问题讨论】:

  • 它不仅在第一次匹配时递增,它总是将scoreCntr 设置为零,递增它,然后将该值(始终为一)分配给lblScoreCntr.Content

标签: c# wpf counter


【解决方案1】:

每次运行该方法时,您都会将计数重置为 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;
}

【讨论】:

    【解决方案2】:

    您需要将 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多