簡體   English   中英

C# 數組中所有項目的消息框

[英]C# MessageBox For All Items In Array

我正在嘗試遍歷一個字符串數組並將它們全部顯示在一個消息框中。 我現在的代碼是這樣的:

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

這顯然會為每個項目顯示一個消息框,有什么辦法可以在循環外的消息框中一次顯示它們嗎? 如果可能的話,我將使用 \n 來分隔項目,謝謝。

您可以將數組中的各個字符串組合成一個字符串(例如使用string.Join方法),然后顯示連接的字符串:

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

您可以使用string.Join將它們組合成一個字符串。 不要,使用\\n ,最好使用Environment.NewLine

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

我會看到兩種常見的方法來做到這一點。

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

像這樣將消息框置於循環之外

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

string message5 = "";

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

試試用這個..

using System.Threading;



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


        foreach (var item in array)
        {

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


        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM