How do you iterate through the member variables of an object?
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开发者_如何学Python 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:
Public Sub DoLoad()
Dim controls = Me.GetType.GetFields(BindingFlags.Instance Or BindingFlags.NonPublic) _
.Where(Function(f) f.FieldType.IsSubclassOf(GetType(AresControl))) _
.Select(Function(f) f.GetValue(Me)).Cast(Of AresControl)()
For Each c In controls
Me.Controls.Add(c)
Next
End Sub
Sure - add methods to that object to allow you to what you want and hide the details. I think this is where encapsulation is your friend.
精彩评论