首页 > 解决方案 > C# - 多个 switch 案例/语句与嵌套 If

问题描述

我有一个带有 3 个列表框的 Windows 应用程序。用户可以从每个列表框中选择一个项目,然后根据所选项目的具体组合得到一个输出。

我最初为此使用嵌套的 if 语句,但有没有更简单的方法?

仅两个列表框的示例:

// if the first option in Vendors is chosen AND first option in Models is chosen
if (vendorListBox.SelectedIndex == 0)
{
    if (modelListBox.SelectedIndex == 0)
    {
        outputTextBox.Text = "This is your answer";
    }

此代码在单击显示按钮时运行

标签: c#

解决方案


不需要ifs和switch。

我会为此使用一个包含 3 个整数值和一个字符串的查找列表,它允许在您的代码之外进行动态维护,例如在数据库中。快速而肮脏的例子..

List<Tuple<int,int,int, string>> PrepareLookupTable()
{
  var lst = new List<Tuple<int,int,int, string>>();
  lst.Add(new Tuple<int,int,int,string>(0,0,0,"Your answer"));
  lst.Add(new Tuple<int,int,int,string>(0,1,0,"Original answer"));
  lst.Add(new Tuple<int,int,int,string>(0,2,1,"Really rediculous answer"));
  // .. or fill the list from somewhere else database.. or json..
  return lst;
}

string ShowMessageForSelection(List<Tuple<int,int,int, string> lst)
{
  var sel1 = ListBox1.SelectedIndex;
  var sel2 = ListBox2.SelectedIndex;
  var sel3 = ListBox3.SelectedIndex;
  var t = lst.FirstOrDefault(x=>(sel1==Item1)&&(sel2==Item2)&&(sel3==Item3));
  if (t!=null) outputTextBox.Text = t.Item4;
 }

 // to use: 
 //    var lst = PrepareLookupTable();
 //    ShowMessageForSelection(lst);   

推荐阅读