1

OK, that question sounds maybe a little confusing so I'll try to explain it with an example.

Pretend you have an object like this:

Class Something
    Private varX As New Integer
    Private varY As New String

'[..with the associated property definitions..]

    Public Sub New()
    End Sub

End Class

And another with:

Class JsonObject
    Inherits Dictionary(Of String, String)

    Public Function MakeObject() As Object 'or maybe even somethingObject 
        Dim somethingObject As New Something()

        For Each kvp As KeyValuePair(Of String, String) In Me
            'Here should happen something to use the Key as varX or varY and the Value as value for the varX or varY
            somethingObject.CallByName(Me, kvp.Key, vbGet) = kpv.Value

        Next

        return somethingObject
    End Function

End Class

I've got the 'CallByMe()' function from a previous question of myself

Community
  • 1
  • 1
Highmastdon
  • 6,960
  • 7
  • 40
  • 68

1 Answers1

0

CallByName works different from the way you are trying to use it. Look at the documentation, it will tell you that in this particular case the correct usage would be

CallByName(Me, kvp.Key, vbSet, kpv.Value)

However, the function CallByName is part of a VB library that isn’t supported on all devices (notably it isn’t included in the .NET Mobile framework) and consequently it’s better not to use it.

Using proper reflection is slightly more complicated but guaranteed to work on all platforms.

Dim t = GetType(Something)
Dim field = t.GetField(kvp.Key, BindingFlags.NonPublic Or BindingFlags.Instance)
field.SetValue(Me, kvp.Value)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Thanks for pointing out the working version of CallByName(). I should've looked in the documentation, yes. But I don't really get the reflection to work (yes, I know this isn't the place to ask for working source code but to get pointed in the right direction...). – Highmastdon Jun 13 '12 at 12:39
  • What i want furthermore is to make this generic for any kind of object by passing the 'objectTypeName' of the desired object the Dictionary should be 'deserialized' to. So I thought about `MakeObject(ByVal ObjectTypeName As String)`. So I could make an variable `As` that particular type. Is that possible? – Highmastdon Jun 13 '12 at 12:59
  • @Highmastdon No, that’s not possible. You can however pass a `System.Type` instance to the method and then use `Activator.CreateInstance` to create that type – with some limitations (take a look at the documentation). A generic method might be the better choice though. Incidentally, why don’t you take an [existing JSON deserialiser](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx) which does exactly that? Finally, the code I posted should work as-is. However, note the small change I just made (bug fix). – Konrad Rudolph Jun 13 '12 at 13:19