条件消息框

时间:2013-04-06 07:58:19

标签: c#

我正在制作一个脚本来显示特定的MessageBoxes,如果满足不同的条件。 我有8个要检查的条件,如果它们是“0”或“1”,则每个条件都必须显示不同的MessageBox。

我的代码的缩写示例如下:

// Similar if(y[1] == "1") statements above with similar Messages but without the corresponding fruit(s)

if (y[2] == "1")
{ MessageBox.Show("Multiple goods required! Please get the following
                   items off the shelves" + Environment.NewLine +
                   "1. Apple" + Environment.NewLine + "2. Pear" +
                   Environment.NewLine + "3. Orange");
}

else if (y[2] == "0")
{ MessageBox.Show("Multiple goods required! Please get the following
                   items off the shelves" + Environment.NewLine +
                   "1. Apple" + Environment.NewLine + "2. Pear");
}

我对C#的了解非常基础,但我愿意学习!请帮忙!

2 个答案:

答案 0 :(得分:1)

我会有条件地发送消息,并编写一次显示消息框的代码:

string msg = "Multiple goods required! Please get the following items off the shelves";

if(y[2] == "0" || y[2] == "1")
{
    msg += Environment.NewLine + "1. Apple"
            + Environment.NewLine + "2. Pear";

    if (y[2] == "1")
        msg += Environment.NewLine + "3. Orange";

    MessageBox.Show(msg);
}

我刚刚将上述内容等同于您的代码,否则我认为它可以写得更好。

还可以考虑使用String.FormatStringBuilder来创建邮件,而不是连接小字符串。

答案 1 :(得分:0)

如果您的问题是如何更容易地显示消息框,那就是这样:

for(int i =0;i<y.length;i++){
            if(y[i] == 0){
                MessageBox.Show("Multiple goods required! Please get the following
                   items off the shelves" + Environment.NewLine +
                   "1. Apple" + Environment.NewLine + "2. Pear");
            }
            else if(y[i] == 1){
                MessageBox.Show("Multiple goods required! Please get the following
                   items off the shelves" + Environment.NewLine +
                   "1. Apple" + Environment.NewLine + "2. Pear" +
                   Environment.NewLine + "3. Orange");
            }
        }

如果这不是您的问题,请告诉我,我会回来并尝试提供帮助