将结构添加到结构列表的简便方法

Convenient way to add a structure to a list of structures

我定义了这样的结构:

Private Structure udtString2
    Dim String1 As String
    Dim String2 As String
End Structure

现在我想用值填充 udtString2 的列表,我想以一种方便、结构良好且易于阅读的方式来完成。

请问是否可以做这样的事情?

Dim n As New List(Of udtString2)

'Pseudocode

n.Add(udtString2("TextA1", "TextA2"))
n.Add(udtString2("TextB1", "TextB2"))

或者如果有任何其他人可以像这样很好地看到它。

你可以试试这个:

n.Add(New udtString2() With { .String1 = "TextA1", .String2 = "TextB1" })
...
...
...

此外,您可以使用集合初始值设定项来使其更紧凑,而不是随后调用 n.Add

为您的结构定义一个构造函数:

Private Structure udtString2
    Dim String1 As String
    Dim String2 As String

    Public Sub New (s1 as String, s2 As String)
        String1 = s1
        String2 = s2
    End Sub
End Structure

然后你几乎可以随心所欲地使用它:

n.Add(new udtString2("TextA1", "TextA2"))
n.Add(new udtString2("TextB1", "TextB2"))