0

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?

EnriMR
  • 3,924
  • 5
  • 39
  • 59
Gibbs
  • 1
  • 1
  • Can you please tell us why you want to use a string instead of directly accessing the objects? Is the caller code in another dll? Anyway, you could use two dictionaries, one in SElements and one in CParticle with key: fieldName value: object. Fill it in the constructor manually or via reflection. – Alex B. Feb 11 '16 at 10:34
  • Possible duplicate of [Dynamically invoke properties by string name using VB.NET](http://stackoverflow.com/questions/240836/dynamically-invoke-properties-by-string-name-using-vb-net) – Ňɏssa Pøngjǣrdenlarp Feb 11 '16 at 13:09
  • You are right @Alex B., I'd prefer a Dictionary so that reflection is only called once upon creation of the instance. Maybe stupid additional question, as im cycling through the fields in my class, how do i get he reference to the object itself? The name is clear: 'field.Name' – Gibbs Feb 11 '16 at 16:36
  • I don´t know if I understood you correctly but the `Me` keyword gives you the current instance of th object in scope – Alex B. Feb 12 '16 at 11:25

0 Answers0