C# If loop within a for loop within a if loop

标签 c# if-statement

如果可以的话,我想减少这段代码:

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/

相关文章:

c - 查找两个值之间的孪生素数

c# - CollectionEditor 的父级

c# - 如何为当前用户(Sitecore)添加新的访客标签?

c# - 如何将 Graphic Raycaster 与 WorldSpace UI 结合使用?

javascript - setInterval 用于运行带有 if 语句的函数不起作用

java - 金钱累积按钮

java - 在 Java 中使用“=?”比较两个值

java - 如何使用德摩根法java重构if语句

c# - MVC - 如何从 URL 请求并保存 pdf 文件

c# - 无法读取配置部分 'configsections',因为它缺少部分声明