数组中所有项目的 C# 消息框

问题描述 投票:0回答:5

我正在尝试迭代字符串数组并将所有字符串显示在一个消息框中。我目前的代码是这样的:

string[] array = {"item1", "item2", "item3"};
foreach(item in array)
{
   MessageBox.Show(item);
}

这显然会为每个项目带来一个消息框,有什么方法可以在循环外的消息框中一次显示它们?我将使用 如果可能的话,将物品分开,谢谢。

c# arrays messagebox
5个回答
12
投票

您可以将数组中的各个字符串组合成单个字符串(例如使用

string.Join
方法),然后显示连接的字符串:

string toDisplay = string.Join(Environment.NewLine, array); 
MessageBox.Show(toDisplay);

5
投票

您可以使用

string.Join
将它们变成一根字符串。不要,用
\n
,最好用
Environment.NewLine

string msg = string.Join(Environment.NewLine, array);

3
投票

我会看到两种常见的方法来做到这一点。

        // Short and right on target
        string[] array = {"item1", "item2", "item3"};
        string output = string.Join("\n", array);
        MessageBox.Show(output);


        // For more extensibility.. 
        string output = string.Empty;
        string[] array = { "item1", "item2", "item3" };
        foreach (var item in array) {
            output += item + "\n"; 
        }

        MessageBox.Show(output);

1
投票

像这样将消息框从循环中取出

string[] array = {"item1", "item2", "item3"};

string message5 = "";

foreach (string item in array)
{
    message5 += (item + "\n") ;
  
}
MessageBox.Show(message5);

0
投票

尝试使用这个..

using System.Threading;



string[] array = {"item1", "item2", "item3"};


        foreach (var item in array)
        {

            new Thread(() =>
            {
                MessageBox.Show(item);
            }).Start();


        }
© www.soinside.com 2019 - 2024. All rights reserved.