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?

4
  • 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. Commented Feb 11, 2016 at 10:34
  • Possible duplicate of Dynamically invoke properties by string name using VB.NET Commented Feb 11, 2016 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' Commented Feb 11, 2016 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 Commented Feb 12, 2016 at 11:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.