【发布时间】:2020-09-27 13:00:27
【问题描述】:
我有这个 c# 代码
progressBar1.Increment(1);
if (progressBar1.Value > 5 && progressBar1.Value < 10)
{
label1.Text = "Some text...";
timer1.Stop();
timer1.Start();
timer1.Interval = 1000;
}
else if (progressBar1.Value > 10 && progressBar1.Value < 15)
{
label1.Text = "Some text 2...";
timer1.Interval = 250;
}
else if (progressBar1.Value > 15 && progressBar1.Value < 30)
{
label1.Text = "Some text 3...";
}
else if (progressBar1.Value > 30 && progressBar1.Value < progressBar1.Maximum)
{
label1.Text = "Some text 4...";
timer1.Interval = 100;
}
else if (progressBar1.Value == progressBar1.Maximum)
{
timer1.Stop();
const string message = "Some cool popup message";
const string caption = "Test";
MessageBox.Show(message, caption, MessageBoxButtons.OK);
Close();
}
我确定这段代码很糟糕,我不是真正的程序员,我只是尝试创建一些有趣的应用程序。我怎样才能摆脱这些冗长的 else if 语句并用更好的东西替换它?我一直在寻找答案和提示,但没有一个对我有帮助。
【问题讨论】:
-
你可以做一个switch语句。但存在逻辑错误。如果 progressBar1.Value == 10 会发生什么?
-
最简单的方法是删除条件中的一项。 if
-
您是否注意到 if 值将是 5.10.15 或 30,因为您使用了 而不是 >= 或
-
当 value == 10 等时实际上什么都没有发生,它保留以前的 label1.text 并在 value 为 11 时更改它等等。运行程序时我没有遇到任何错误。
标签: c# .net visual-studio performance if-statement