1

我写了以下代码:

Public Class Form1

Private Structure udtThing
    Dim SomeText As String
    Dim SomeElements() As String
    Public Shared Function CreateInstance() As udtThing
        Dim result As New udtThing
        result.SomeText = String.Empty
        ReDim result.SomeElements(2)
        result.SomeElements(0) = String.Empty
        result.SomeElements(1) = String.Empty
        result.SomeElements(2) = String.Empty
        Return result
    End Function
End Structure

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim nThings() As udtThing
    nThings = Array.CreateInstance(GetType(udtThing), 10)

End Sub
End Class

我部分工作,nThings 变成了 11 个 udtThings 的数组。但是 .SomeElements 并没有重新调整为 3 个 String.Empty 字符串,而是“Nothing”。

有人看到我哪里出错了吗?

非常感谢你!

4

1 回答 1

3

按照设计,需要 Redim。Array.CreateInstance() 不会执行该操作,它无法猜测所需的大小。你必须帮助:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim nThings(10) As udtThing
    For ix As Integer = 0 To UBound(nThings)
        nThings(ix) = udtThing.CreateInstance()
    Next
End Sub
于 2012-12-22T18:17:46.510 回答