2013-03-06 44 views
0

此問題是VB ReDim of member field programmatically的後續操作。在數組的尺寸適當後,我嘗試設置元素的值,但是當我嘗試分配第一個值(MySB.AssignValues(0,「B」,0,7.6))時,我在運行時得到一個異常VB以編程方式分配成員字段

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

哪條線AssignValues的拋出的錯誤? – Melanie 2013-03-06 17:32:08

+0

「f.SetValue(TheValue,TheIndex)」 – scriptOmate 2013-03-06 17:34:07

回答

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 

,或者如果你知道數組將永遠是雙數組,你可以直接將它轉換到:

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 
+0

效果很好。謝謝!我無法弄清楚如何獲得類字段的實例,然後設置數組的元素。 – scriptOmate 2013-03-07 20:50:57