Marsan001

Hello,

we use reflection and want to set class-contents at runtime. This works well for simple members, even for class-members of the class. But not for Arrays. Here a code snippet:

Private Sub ExploreClass2(ByVal t As Type, ByVal lvl As Integer, ByVal cls As Object)

For Each p As System.Reflection.PropertyInfo In t.GetProperties()

If p.PropertyType.IsClass Then

If p.PropertyType.IsArray = False Then

' Normal Class content - works fine

Dim oNew As Object = ***.CreateInstance(p.PropertyType.ToString)

p.SetValue(cls, oNew, Nothing)

Else

' Array Content

Dim oNew(3) As Object

For i As Integer = 0 To 3

oNew(i) = ***.CreateInstance(p.PropertyType.ToString.Replace("[]", ""))

Next

' this does not work - how can "cls" be set with the contents of oNew

p.SetValue(cls, Nothing, oNew)

End If

End If

Next

End Sub

The red line is the problem, how can we set the value of the array

Mark




Re: Common Language Runtime Use System.Reflection.PropertyInfo.SetValue for array

ARK88

I think you just need to swap "Nothing" with "oNew"...

Here's kind of what I did for the array section of your code (I changed the one part of it where you stripped off the brackets, because if the brackets ever changed to something else you'd have to change your code)

Code Snippet

' Create an array of 4 items based on the element type

' of the property you are referencing.

Dim oNew As Object = Array.CreateInstance(p.PropertyType.GetElementType(), 4)

' Set some values in the array.

For i As Int32 = 0 To CType(oNew, Array).Length - 1

oNew(i) = Activator.CreateInstance(GetType(Class1))

Next

p.SetValue(cls, oNew, Nothing)





Re: Common Language Runtime Use System.Reflection.PropertyInfo.SetValue for array

Marsan001

...this solves my problem. I am still unsure of the meaning of the third parameter in SetValue... But anyway - Thanks.