优化 if 语句

本文关键字:语句 if 优化 | 更新日期: 2023-09-27 18:18:09

我正在尝试在循环中做ifs。编译器说"发生了未处理的异常"。有什么想法吗?注释的代码正在工作。为的那个不是。对于应该更优化。编辑:抱歉忘了说所有组合框和TetBox都在数组中。

        ComboBox[] ComboBoxes = new ComboBox[3];
        ComboBoxes[0] = comboBox1;
        ComboBoxes[1] = comboBox2;
        ComboBoxes[2] = comboBox3;

工作代码:

if (comboBox1.Text == "Cheese" || comboBox1.Text == "Vegetable" || comboBox1.Text == "Meat")
{
    if (comboBox2.Text == "Cheese" || comboBox2.Text == "Vegetable" || comboBox2.Text == "Meat")
    {
        if (comboBox3.Text == "Cheese" || comboBox3.Text == "Vegetable" || comboBox3.Text == "Meat")
        {
            return true;
        }
        else { comboBox3.Text = "Wrong input"; return false; }
     }
     else { comboBox2.Text = "Wrong input"; return false; }
 }
 else { comboBox1.Text = "Wrong input"; return false; }

最佳不工作版本:

int isvalid = 0;
for (int i = 0; i < 3; i++)
{
    if (ComboBoxes[i].Text == "Cheese" || ComboBoxes[i].Text == "Vegetable" || ComboBoxes[i].Text == "Meat")
    {
        isvalid++;
    }
    else { ComboBoxes[i].Text = "Wrong input"; }
}
if (isvalid == 3)
{ 
    return true; 
}
else { return false; }

优化 if 语句

int isvalid = 0;
List<string> foods = new List<string> { "Cheese", "Vegetable", "Meat" };
List<string> cbNames = new List<string> { "comboBox1", "comboBox2", "comboBox3" }; //If you have more than the three comboBoxes
foreach(Control cb in this.Controls)
{
    if(cb is ComboBox)
    {
        if(foods.Contains((ComboBox)cb.Text) &&  cbNames.Contains((ComboBox)cb.Name))
        //Only use the second condition if you have more than the three comboBoxes
            isvalid++;
        else
            (ComboBox)cb.Text = "Wrong Input";
    }
}
if (isvalid == 3)
    return true;
return false;

这使用了一个foreach,这是cb的来源,它与循环遍历每个组合框相同,这里有一些关于forone的更多信息

在您最近的编辑之后,这现在可以更好地工作

int isvalid = 0;
List<string> foods = new List<string> { "Cheese", "Vegetable", "Meat" };
foreach(ComboBox cb in ComboBoxes)
{
    if(foods.Contains(cb.Text))
        isvalid++;
    else
        cb.Text = "Wrong Input";
}
if (isvalid == 3)
    return true;
return false;