如何优化此代码

本文关键字:代码 优化 何优化 | 更新日期: 2023-09-27 18:20:36

我有以下代码:

    if (userValueSom01 == realResult01)
    {
        //answer = correct
        //count +1 for overall good answers
        WpfApplication1.Properties.Settings.Default.totallGood++;
        //count for good +1
        answerThisWindowGood++;
        //make visible the green logo
        Som01G.Visibility = Visibility.Visible;
    }
    else
    {
        //answer = wrong
        //count +1 for overall wrong answers
        WpfApplication1.Properties.Settings.Default.totallWrong++;
        //count for wrong +1
        answerThisWindowWrong++;
        //make visible the red logo
        Som01W.Visibility = Visibility.Visible;
        labelSom01Check.Content = Convert.ToString(realResult01);
    }

现在的重点是,这种情况发生了XX次,其中XX是一个数字,与你在代码中看到的数字相对应。所以在上面的例子中,XX是01。*注意,输入中的01,结果中的01也是

在对c#还不太深入的时候,一开始我认为当XX是20时,我需要将上面的部分复制20次,并更改数字。现在这似乎很麻烦,我想应该有一些更聪明的方法来处理这个问题,重点是,我想不出该怎么做(如上所述,我还没有深入研究c#)。

有人能把我推向正确的方向吗?

提前谢谢。

---编辑1---谢谢Miika L。与您的解决方案略有不同:

public bool checkValue(double value, int result, Image controlG, Image controlW, Label label)
        {
            if (value == result)
            {
                //... Do stuff
                controlG.Visibility = Visibility.Visible;
                return true;
            }
            else
            {
                //... Do other stuff
                controlW.Visibility = Visibility.Visible;
                label.Content = result.ToString();
                return false;
            }
        }

现在我真的可以打电话了:bool test=checkValue(userValueSom01,realResult01,Som01G,Som02W,labelSom01Check);

作品:)thanx!

如何优化此代码

把它写成函数怎么样?

public bool checkValue(
    int value,
    int result,
    Control controlG,
    Control controlW,
    Label label)
{
    if (value == result)
    {
        ... Do stuff
        controlG.Visibility = Visibility.Visible;
    }
    else
    {
        ... Do other stuff
        controlW.Visibility = Visibility.Visible;
        label.Content = result.ToString();
    }
}

与其像userValueSom01那样在名称中定义数百个带有数字的变量,realResult01最好使用数组字典(如果合适的话)。