0

这个问题是成员字段的 VB ReDim 编程的后续问题。适当确定数组的尺寸后,我尝试设置元素的值,但在运行时尝试分配第一个值时出现异常 (MySB.AssignValues(0, "B", 0, 7.6))

System.InvalidCastException was unhandled
HResult=-2147467262
Message=Object cannot be stored in an array of this type.
Source=mscorlib

Module TestSetArray

    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 2
        End Function

        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

        Public Sub AssignValues(MainIndex As Integer, TheName As String, TheIndex As Integer, TheValue As Double)
            Dim f = MyBS(MainIndex).GetType.GetMember(TheName)
            f.SetValue(TheValue, TheIndex)
        End Sub

    End Class

    Sub Main()
        Dim MySB As SB = New SB
        MySB.DimArrays()
        MySB.AssignValues(0, "B", 0, 7.6)
        MySB.AssignValues(0, "B", 1, 8.2)
    End Sub

End Module

提前致谢。

4

1 回答 1

0

问题是 GetMember 方法返回的是 MemberInfo 类型的数组,而不是类的双精度数组。如果您改用 GetField,您可能会更轻松。您必须调用 GetValue 并将其结果转换为 Array 才能使用 SetValue 设置值。

Public Sub AssignValues(MainIndex As Integer, TheName As String, TheIndex As Integer, TheValue As Double)
    Dim f = MyBS(MainIndex).GetType().GetField(TheName)
    Dim doubleArray = DirectCast(f.GetValue(MyBS(MainIndex)), Array)
    doubleArray.SetValue(TheValue, TheIndex)
End Sub

或者如果您知道该数组将始终是一个 Double 数组,您可以将其直接转换为:

Public Sub AssignValues(MainIndex As Integer, TheName As String, TheIndex As Integer, TheValue As Double)
    Dim f = MyBS(MainIndex).GetType().GetField(TheName)
    Dim doubleArray = DirectCast(f.GetValue(MyBS(MainIndex)), Double())
    doubleArray(TheIndex) = TheValue
End Sub
于 2013-03-07T17:40:32.423 回答