0

我正在尝试根据读取文件来重新调整成员数组。我不知道该怎么做。这是我尝试过的,但它不起作用。

Public Class BS
    Public A() As String
    Public B() As Double
    Public C() As Double
End Class

Public Class SB

    Public MyBS() As BS

    'ReadFieldString is a function that returns a string of the field name of Class BS,
    'i.e., A, B or C.  For test purpose, retun a constant
    Public Function ReadFieldString() As String
        Return "B"
    End Function

    'GetArrayDim is a function that returns an integer, which is the size of the array
    'of that field name. For test purpose, retun a constant
    Public Function GetArrayDim() As Integer
        Return 1
    End Function

    Public Sub DimArrays()
        ReDim MyBS(3)
        Dim i As Integer
        For i = 0 To MyBS.Length - 1
            'Try to ReDim the member of MyBS
            ReDim MyBS(i).GetType.GetField(ReadFieldString)(GetArrayDim)
        Next()
    End Sub

End Class

ReDim 语句出现错误“表达式是一个值,因此不能成为赋值的目标”。提前致谢。

4

1 回答 1

1

我不确定ReDim这样的工作方式。将代码更改为此将实现我相信您所追求的:

Public Sub DimArrays()
    ReDim MyBS(3)
    Dim i As Integer
    For i = 0 To MyBS.Length - 1
        MyBS(i) = New BS()
        Dim f = GetType(BS).GetField(ReadFieldString())
        f.SetValue(MyBS(i), Array.CreateInstance(f.FieldType.GetElementType(), GetArrayDim()))
    Next
End Sub

但是,我认为更好的方法是在 BS 构造函数中指定数组大小。

于 2013-03-04T22:10:39.980 回答