如果可以的话,我想减少这段代码:
class Alarm
{
internal static void isGreaterThanOrBelowValue(int min, int max, int now, int i)
{
MainWindow mw = new MainWindow();
if (now < min && now !=0)
{
if(i == 1)
{
mw.TxtBox1.Foreground = new SolidColorBrush(Colors.Red);
}
if (i == 2)
{
mw.TxtBox2.Foreground = new SolidColorBrush(Colors.Red);
}
if (i == 3)
{
mw.TxtBox3.Foreground = new SolidColorBrush(Colors.Red);
}
}
if (now > max && now !=0)
{
if(i == 1)
{
mw.TxtBox1.Foreground = new SolidColorBrush(Colors.Red);
}
if (i == 2)
{
mw.TxtBox2.Foreground = new SolidColorBrush(Colors.Red);
}
if (i == 3)
{
mw.TxtBox3.Foreground = new SolidColorBrush(Colors.Red);
}
}
}
我想做以下事情:
i 可以在 1 到 33 之间。
我可以获取文本框名称 (TxtBox1) 等
我想减少 if 语句,这样每个较大的 if 语句就没有 32 个 if 语句。
谢谢! :)
最佳答案
只需为文本框使用数组,如下所示:
internal static void isGreaterThanOrBelowValue(int min, int max, int now, int i)
{
MainWindow mw = new MainWindow();
TextBox[] tbList = new TextBox[] { mw.TxtBox1, mw.TxtBox2, mw.TxtBox3 };
if (now !=0 && (now < min || now > max))
{
tbList[i-1].Foreground = new SolidColorBrush(Colors.Red);
}
}
如果文本框不改变,您也可以在函数外部构建数组作为类成员,这样您就不会在每次调用函数时都重建它:
static MainWindow mw = new MainWindow();
static TextBox[] tbList = new TextBox[] { mw.TxtBox1, mw.TxtBox2, mw.TxtBox3 };
internal static void isGreaterThanOrBelowValue(int min, int max, int now, int i)
{
if (now !=0 && (now < min || now > max))
{
tbList[i-1].Foreground = new SolidColorBrush(Colors.Red);
}
}
关于C# If loop within a for loop within a if loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33927132/