C# 如何使用多个列表框组合格式化代码

C# 如何使用多个列表框组合格式化代码,c#,C#,几天前我问了一下,得到了一些很好的反馈,但我想为我正在做的事情提供更多的背景 我有3个列表框,每个都可能有10多个选项。用户选择一些选项组合(每个文本框中有一个选项)。基于此,将显示特定的输出 我现在看到的只是嵌套的if语句。虽然这样做有效,但我觉得它很快就会变得一团糟。我只对每个测试框中的第一个选项进行了测试 private void displayButton_Click(object sender, EventArgs e) { if (scriptGenButt

几天前我问了一下,得到了一些很好的反馈,但我想为我正在做的事情提供更多的背景

我有3个列表框,每个都可能有10多个选项。用户选择一些选项组合(每个文本框中有一个选项)。基于此,将显示特定的输出

我现在看到的只是嵌套的if语句。虽然这样做有效,但我觉得它很快就会变得一团糟。我只对每个测试框中的第一个选项进行了测试

 private void displayButton_Click(object sender, EventArgs e)
    {
        if (scriptGenButton.Checked)
        {
            // if the first option in Vendors is chosen AND first option in Models is chosen AND first option in Options is chosen
            if (vendorListBox.SelectedIndex == 0)
            {
                if (modelListBox.SelectedIndex == 0)
                {
                    if (optionListBox.SelectedIndex == 0)
                    {
                        outputTextBox.Text = "Option1!";
                    }
                }
            }

在这种情况下你们会怎么做?我知道有些人提到字典。

不要像那样使用嵌套的if,请使用&&运算符

if(scriptGenButton.Checked && vendorListBox.SelectedIndex == 0 && modelListBox.SelectedIndex == 0 && ...) {

}

不要像那样使用嵌套的if,请使用&&运算符

if(scriptGenButton.Checked && vendorListBox.SelectedIndex == 0 && modelListBox.SelectedIndex == 0 && ...) {

}

我可以提供以下解决方案。向元组添加值。然后比较元组

var values = (scriptGenButton.Checked, vendorListBoxSelected.Index, modelListBoxSelected.Index, optionListBoxSelected.Index);

if (values == (true, 0, 0, 0))
{
    outputTextBox.Text = "Option1!";
}
else if (values == (true, 0, 0, 1))
{
    outputTextBox.Text = "Option2!";
}
// and so on

我可以提供以下解决方案。向元组添加值。然后比较元组

var values = (scriptGenButton.Checked, vendorListBoxSelected.Index, modelListBoxSelected.Index, optionListBoxSelected.Index);

if (values == (true, 0, 0, 0))
{
    outputTextBox.Text = "Option1!";
}
else if (values == (true, 0, 0, 1))
{
    outputTextBox.Text = "Option2!";
}
// and so on

使用
&&
而不是嵌套if这似乎是一本不错的读物:你使用哪种语言版本?你可以使用模式匹配吗?@AlexanderPetrov我如何为你检查?我正在使用VisualStudio2019@RandRandom那看起来效率更高!现在你正在使用.NET核心还是.NET框架?使用
&&
而不是嵌套if这似乎是一本不错的读物:你使用哪种语言版本?你可以使用模式匹配吗?@AlexanderPetrov我如何为你检查?我正在使用VisualStudio2019@RandRandom那看起来效率更高!现在你正在使用.NETCore还是.NETFramework?这太神奇了。很简单,我能理解它为什么有效。。。非常感谢你!这太神奇了。很简单,我能理解它为什么有效。。。非常感谢你!