c# - 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";
}
此代码在单击显示按钮时运行
解决方案
不需要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);
推荐阅读
- java - 将可选参数传递给 JdbcTemplate
- r - 如何使用 options() 从 R 中完全删除全局选项
- javascript - 如何从 L.Routing.control 获取距离和时间?
- php - div img src 不显示随机图像
- javascript - 了解原型链是如何工作的?
- html - PhpStorm 无法正确识别 HTML 标签
- python - 从两个for循环python获取x,y值
- wordpress - 如何在我的网站上查看和下载私人视频(在私人 Pro Vimeo 个人资料上)?
- javascript - 如何从中获取特定的密钥?
- java - Mac JDK11:线程“主”java.lang.NoClassDefFoundError 中的异常:java/sql/SQLException