首页 > 解决方案 > 简化文本框中的 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";

标签: c#

解决方案


我对你的问题的理解是你想测试一些等式的组合。本质上,您在可能的输入和输出之间有一个“真值表”/映射。有几种方法可以做到这一点;下面是使用字典将可能的输入映射到可能的输出的示例:

在您的实际功能中输入以下内容:

//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";

推荐阅读