VB以编程方式分配成员字段

时间:2013-03-06 17:28:51

标签: vb.net gettype setvalue

这个问题是VB ReDim of member field programmatically的后续问题。在适当地确定数组的大小之后,我尝试设置元素的值,但是当我尝试分配第一个值时,我在运行时得到一个异常(MySB.AssignValues(0,“B”,0,7.6))< / p>

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

问题是GetMember方法返回一个MemberInfo类型的数组,而不是类的double数组。如果你使用GetField,你可能会更容易。您必须调用GetValue并将其结果转换为数组才能使用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