是否可以构建一个 MessageBox 消息,然后将其传递给消息框以包含新行?

Is it possible to build a MessageBox message that is then passed to a message box to include new lines?

我正在尝试为用户生成一条消息,其中 returns 缺少清单项目的列表。我的问题:有没有一种方法可以构建一条消息,然后将其传递给包含新行的 MessageBox。我考虑过重载该方法以接受各种数量的单独消息,但必须有一种更优雅的方法来做到这一点。下面是我设计的 class 来处理此消息收集、显示和将来导出为更方便的格式。

Public Class clsChecklistMissingItems

Private Shared iWrong As Integer = 0 'Number of items wrong.
Private Shared sMissingItems() As String 'Will use the number of items wrong.

Public Shared Sub CollectItem(ByVal mess As String) 'Saves the message passed to it.


    ReDim Preserve sMissingItems(iWrong) 'Resize the array based on the counter.
    sMissingItems(iWrong) = mess 'Assign the message to the missing items string array.
    iWrong = iWrong + 1 'Increment the counter (may give us +1 

End Sub

Public Sub DisplayList() 'Displays the message at the end of the execution.
    'Can this be generated procedurally?

    MessageBox.Show("There were " & iWrong & " missing or incorrect items." & vbNewLine &
                    sMissingItems(iWrong))

End Sub End Class

我的替代解决方案是编写一个格式类似于文本框的表单,其行为类似于文本框,但具有所有描述的功能。

使用数组不是最佳选择。 .NET 有大量内置集合 类,它们远优于数组,例如 List<T>。我知道当您来自 Visual Basic 的其他 "flavors"(VBScript、VBA 等)时很想使用数组,因为这是您所熟悉的,但您应该了解可用的内容在 .NET FCL 中。

您可以使用循环和 StringBuilder 来构建您的消息列表:

Dim wrongItems As New List(Of String)()

' fill the collection however you do it...
wrongItems.AddRange({"Reason 1", "Reason 2", "Reason 3"})

Dim sb As New StringBuilder()

For Each item In wrongItems
    sb.AppendLine(item)
Next

MsgBox(String.Format("There were {0} missing or incorrect items.",
                     wrongItems.Count) & vbNewLine & sb.ToString())

在与我的同事交谈后,有人向我指出 VB.NET 有一个马车 return 换行符,旨在连接成一个字符串以表示一个新行。

Public Sub DisplayList()

    Dim sMessage As String = ""

    For i As Integer = 0 To sMissingItems.Length - 1
        sMessage = sMessage & sMissingItems(i) & vbCrLf
    Next

    MessageBox.Show(sMessage)

End Sub

此时我还没有机会使用列表而不是数组来实现。