c# - 简化文本框中的 if 语句?
问题描述
不幸的是,我不知道这个问题是否已经被问到,这就是我在这里做的原因。我想知道你是否可以在这里简化一个例子:
if (textbox1.text == "" && textbox2.text == "" && textbox3.text == "") {
label1.text = "Empty boxes.";
}
if (textbox1.text == "is playing" && textbox2.text == "" && textbox3.text == "") {
label1.text = "player is playing";
}
if (textbox1.text == "" && textbox2.text == "online" && textbox3.text == "vip") {
label1.text = "player is online and is vip";
}
如果已经问过这个问题,我真的很抱歉,但我没有找到。问候。
编辑:这是另一个例子
if (textbox1.text != "" && textbox2.text == "" && textbox3 == "")
label1.Text = "1 are not empty"
if (textbox1.text == "" && textbox2.text != "" && textbox3 == "")
label1.Text = "2 are not empty"
if (textbox1.text != "" && textbox2.text != "" && textbox3 == "")
label1.Text = "1 & 2 are not empty"
if (textbox1.text == "" && textbox2.text != "" && textbox3 != "")
label1.Text = "2 & 3 are not empty"
if (textbox1.text != "" && textbox2.text == "" && textbox3 != "")
label1.Text = "1 & 3 are not empty"
if (textbox1.text == "" && textbox2.text == "" && textbox3 == "")
label1.Text = "boxes empty";
解决方案
我对你的问题的理解是你想测试一些等式的组合。本质上,您在可能的输入和输出之间有一个“真值表”/映射。有几种方法可以做到这一点;下面是使用字典将可能的输入映射到可能的输出的示例:
在您的实际功能中输入以下内容:
//put the above to use in finding what value to assign
var key = new ThreeValueKey(textbox1.text, textbox2.text, textbox3.text);
label1.text = ResultMap.TryGetValue(key, out var value) ? value : DefaultResult;
为此,您需要拥有以下课程:
//create some way of holding your "rules".
class ThreeValueKey {
public string Key1 {get;set;}
public string Key2 {get;set;}
public string Key3 {get;set;}
}
...你需要定义你的规则
//map each of the possible rules to the value:
static readonly IDictionary<ThreeValueKey, string> ResultMap = new Dictionary<ThreeValueKey, string>() {
{new ThreeValueKey {Key1 = string.Empty, Key2 = string.Empty, Key3 = string.Empty}, "Empty boxes."}
,{new ThreeValueKey {Key1 = "is playing", Key2 = string.Empty, Key3 = string.Empty}, "player is playing"}
,{new ThreeValueKey {Key1 = string.Empty, Key2 = "online", Key3 = "vip"}, "player is online and is vip"}
};
//if there's no match, what should we do? Assign a default value?
const string DefaultResult = "whatever to put if there's no match";
推荐阅读
- javascript - 在feathersJs中查找服务承诺失败
- docker - 启动命令后 Docker 容器退出
- python - 如何解决 IndexError:列表索引超出范围
- c# - 如果基类没有构造函数,我可以从类继承吗
- c++ - 如何制作可以缩放和绘制的画布 QWidget?
- python-3.x - 如何在 Python 中实现 QT(质量阈值)聚类?
- haskell - 求叶子总和
- python-3.x - Pytorch:ValueError:预期输入batch_size(32)与目标batch_size(64)匹配
- python - Maya Python Script - os.popen tasklist read 超级慢。更快的方式?
- .net - 找不到文件“C:\cfn\ebdata\source_bundle_final.zip”