gpt4 book ai didi

c# - 编写此 if 语句的更好方法?

转载 作者:行者123 更新时间:2023-11-30 19:32:55 24 4
gpt4 key购买 nike

我还有一个问题要问你们这些非常有帮助的人。我使用了很多 if 语句,其中许多只是重复,我确信可以缩短。这是我当前的代码

if (Globals.TotalStands <= 1)
{
ScoreUpdate.StandNo2.Visible = false;
ScoreUpdate.ScoreStand2.Visible = false;
ScoreUpdate.ScoreOutOf2.Visible = false;
}

if (Globals.TotalStands <= 2)
{
ScoreUpdate.StandNo3.Visible = false;
ScoreUpdate.ScoreStand3.Visible = false;
ScoreUpdate.ScoreOutOf3.Visible = false;
}

if (Globals.TotalStands <= 3)
{
ScoreUpdate.StandNo4.Visible = false;
ScoreUpdate.ScoreStand4.Visible = false;
ScoreUpdate.ScoreOutOf4.Visible = false;
}

if (Globals.TotalStands <= 4)
{
ScoreUpdate.StandNo5.Visible = false;
ScoreUpdate.ScoreStand5.Visible = false;
ScoreUpdate.ScoreOutOf5.Visible = false;
}

if (Globals.TotalStands <= 5)
{
ScoreUpdate.StandNo6.Visible = false;
ScoreUpdate.ScoreStand6.Visible = false;
ScoreUpdate.ScoreOutOf6.Visible = false;
}

if (Globals.TotalStands <= 6)
{
ScoreUpdate.StandNo7.Visible = false;
ScoreUpdate.ScoreStand7.Visible = false;
ScoreUpdate.ScoreOutOf7.Visible = false;
}

if (Globals.TotalStands <= 7)
{
ScoreUpdate.StandNo8.Visible = false;
ScoreUpdate.ScoreStand8.Visible = false;
ScoreUpdate.ScoreOutOf8.Visible = false;
}

如您所见,有大量代码可以做一些简单的事情(我也在其他一些表格上这样做,我相信一定有更好的编码方法来获得相同的结果?我我是一个代码菜鸟,所以请保持温柔,代码是 C#,软件是 Visual Studio 2008 pro。

最佳答案

您的大部分属性应该是数组(或其他一些集合)。例如:

ScoreUpdate.StandNo6

可能是这样的:

ScoreUpdate.StandNos[5]

然后您可以使用循环来代替所有那些 if 语句:

for (int i = 0; i < Globals.TotalStands; ++i)
{
ScoreUpdate.StandNos[i].Visible = true;
ScoreUpdate.ScoreStands[i].Visible = true;
ScoreUpdate.ScoreOutOfs[i].Visible = true;
}

或者如果有一个 ScoreUpdates 数组而不是三个单独的数组,这种细微的变化可能会更好:

for (int i = 0; i < Globals.TotalStands; ++i)
{
var scoreUpdate = ScoreUpdates[i];
scoreUpdate.StandNo.Visible = true;
scoreUpdate.ScoreStand.Visible = true;
scoreUpdate.ScoreOutOf.Visible = true;
}

关于c# - 编写此 if 语句的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4588228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com