我正在尝试基于读取文件来重新调整成员数组。我无法弄清楚该怎么做。这是我尝试过的,但它不起作用。
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语句的错误是“表达式是一个值,因此不能成为赋值的目标”。 提前致谢。
答案 0 :(得分: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构造函数中指定数组大小。