I’m building a litle console app that involves a control hierarchy — there are screens, and inside of screens you can compose controls together.
You can add controls to a screen by declaring member variables (which all inherit from AresControl). The control constructor takes a simple coordinate pair. It looks like this:
Public Class IntroScreen : Inherits AresScreen
'Controls
Private LabelSelect As New LabelControl(72, 0)
Private Stats As New StatAreaControl(2, 2)
Private Messages As New MessageAreaControl(22, 45) With {.ListeningForKeys = True}
Then, in the OnLoad event, you have to add all those controls to a collection so we can later iterate through them and do rendering and so on:
Public Sub Screen_Load() Handles MyBase.OnLoad
MyBase.Controls.Add(LabelSelect)
MyBase.Controls.Add(Stats)
MyBase.Controls.Add(Messages)
End Sub
I would like to handle adding the controls to the collection in the base class automatically. Here’s what I had in mind:
- Use reflection to iterate over the member variables
- Pull the ones that inherit from AresControl
- Add them to the collection
This would result in cleaner, convention-based code. But try as I might, I can’t get it to work – I can walk the member variables of a type, but I need to walk the member variables of a live object.
This is possible, right?
You can do it using reflection. In the base class: