递增手势匹配的分数计数器

本文关键字:计数器 | 更新日期: 2023-09-27 17:56:04

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

这是我当前的解决方案,仅在第一场比赛中递增:

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。 最快的解决方法是仅在方法外部声明变量:

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;
}

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