jeudi 11 février 2016

VB.NET - Access variable in class within class by string name

Hi to all,

So here is part of my class structure:

Public Class CParticle

    Public Feature As Double
    Public AreaName As String
    ......  

    Public ElementsWT As SElements      'Elements in wt%
    Public ElementsAT As SElements      'Elements in at%

    Public Sub New()

        ElementsWT = New SElements
        ElementsAT = New SElements

    End Sub

End Class

With this 'subclass':

Public Class SElements

    Public B As Double
    Public C As Double
    Public N As Double
    Public O As Double
    Public F As Double
    ....

End Class

Now I want to access all variables within an instance of CParticle (e.g. called 'Particle') and also its instances of SElements by their name (String).

e.g.: "Feature" should give me access to Particle.Feature

Currently im doing it with reflection:

...
Dim myFieldInfo As FieldInfo

myFieldInfo = GetType(CParticle).GetField("Feature")
If Not myFieldInfo Is Nothing Then myFieldInfo.SetValue(Particle, value)

This works. But how can I access e.g. Particle.ElementsWT.B with the string "ElementsWT.B"? And is there an overall better way to do it besides using reflection?

Thank you for your help!





Aucun commentaire:

Enregistrer un commentaire