0

如果满足不同的条件,我目前正在制作一个脚本来显示特定的 MessageBox。我有 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#知识很基础,但我愿意学习!请帮忙!

4

2 回答 2

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来创建消息,而不是连接小字符串。

于 2013-04-06T08:19:25.007 回答
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");
            }
        }

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

于 2013-04-06T08:10:36.873 回答