views:

323

answers:

3

A number of forms in my project inherit from a base form. It is easy to get at the Controls collection of the derived forms, but I have not found a simple way to access the Components collection, since VS marks this as private.

I assume this could be done with reflection, but I'm not really sure how best to go about it, not having worked with reflection before.

Right now, I'm using a sort of clunky workaround, in which I override a function GetComponents and return an array of the components I'm interested in. This is obviously prone to errors, since it's easy to forget to implement the overridden function or update it when components are added.

If anyone has any tips or can suggest a better way, I'd be glad to hear.

A: 

If you're worried about forgetting to override the function, then make it abstract.

Joel Coehoorn
+1  A: 

If you set the Modifiers property of your components to strict protected makes them accessible without the use of a components collection.

Edit: Discoverability could be done using reflection to walk over each field. Although that might be suboptimal in your case.

Lars Truijens
A: 

@Lars: I don't quite see how that helps, since they're still not discoverable. If I'm missing something, please elaborate.

@Joel: Good idea. That would mean that the whole class (base form) itself would need to be abstract as well, and I'm afraid reworking that might cause too much pain at this point, but I'll definately give it a look. It doesn't solve the problem of forgetting to add components to the list later, though, so while certainly better than my current hack not quite the optimal solution. (I would give you an upvote, but don't have enough rep!)

Tom Juergens