Reflection - SetValue of an array inside a class?

Well, I’ve been working on something for a while, using reflection to accomplish a lot of what I need to do, but I hit a little stumbling block ...

I'm trying to use reflection to populate the properties of an array of a child property ... not sure if this is clear, so it is best explained in code:

Parent class:

Public Class parent
    Private _child As childObject()
    Public Property child As childObject()
        Get
            Return _child
        End Get
        Set(ByVal value As child())
            _child = value
        End Set
    End Property
End Class

Child class:

Public Class childObject
    Private _name As String
    Public Property name As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Private _descr As String
    Public Property descr As String
        Get
            Return _descr
        End Get
        Set(ByVal value As String)
            _descr = value
        End Set
    End Property
End Class

So, using reflection, I'm trying to set the values ​​of an array of child objects through the parent object ...

I tried several methods ... the following is pretty much what I have at the moment (I added sample data just to make things simple):

    Dim Results(1) As String

    Results(0) = "1,2"
    Results(1) = "2,3"
    Dim parent As New parent

    Dim child As childObject() = New childObject() {}
    Dim PropInfo As PropertyInfo() = child.GetType().GetProperties()
    Dim i As Integer = 0
    For Each res As String In Results 
        Dim ResultSet As String() = res.Split(",")
        ReDim child(i)

        Dim j As Integer = 0
        For Each PropItem As PropertyInfo In PropInfo
            PropItem.SetValue(child, ResultSet(j), Nothing)
            j += 1
        Next
        i += 1
    Next
    parent.child = child

This did not abate in PropItem.SetValue with ArgumentException: the property set method was not found.

Does anyone have any idea?

@Jon: -

, , , , ... , ( ).

, , , parent/child. , , / . , . , , , Object [] .

EDIT: , :

Dim PropChildInfo As PropertyInfo() = ResponseObject.GetType().GetProperties()
For Each PropItem As PropertyInfo In PropChildInfo
    PropItem.SetValue(ResponseObject, ResponseChildren, Nothing)
Next

ResponseObject - , ResponseChildren - childObject.

: 'System.Object []' 'childObject []'.

+3
2

-, - , . .

-, , GetProperties - . , . , , , .

-, , , , . , , , , .

, , , , , .

EDIT: , , , . , , . Array.CreateInstance , , .

+4

, ( ) . , Fasterflect :

parent.Property("child").GetElement(index).SetFieldValue("Name",name);

"child" "parent". , , "index" ( ) Name "name".

: .

+1

Source: https://habr.com/ru/post/1703485/


All Articles