tags:

views:

318

answers:

4

Hi,

I have multiple instances of a class in my code, each with difference configs etc. This class has a delegate eventhandler method which receives event from a sender and then need to perform some action with one of the above objects.

I would like to know if reflection can resolve this.

private CatClass cat1;
private CatClass cat2;
private CatClass cat3;

I would like to avoid checking each instance independently to see if it's the object I want. But would instead like to somehow retrieve the object instance which the sending event has identified.

So

private void delegateHandler(string senderName, object sender, CustomEventType evt)
{
     // given reciept of the senderName string,
     // how do I perform an action on say the cat2 object

    // Is it possible to ask the class if it has an object defined
    // called 'cat2' and then proceed with performing an action on that object
}

Thanks for the help.

+1  A: 

That's highly unlikely to achieve the way you want? Out of curiosity, won't sender give you a proper instance? If not, then you should put shot CatClass instances into a Dictionary and search that dictionary when required.

Miha Markic
A: 

C# works better if you "tell" rather than when you "ask".

In other words it would be better to have an interface or base class that has the CatClass member declared in it that would allow you to work with a variable of that interface type or base class instead of using reflection. My only concern is that since the members you are hoping to use are private this will prevent you from using an interface.

Are you really using a handler that digs into the sender via reflection to retrieve private members? Perhaps you ought to re-think your approach.

Andrew Hare
A: 

You can use reflection for that, but I'd suggest not doing it. Reflection is slow and this is unlikely a situation where it is required.

Why not have a dictionary (when you want to look them up by name), a list or an array of CatClass and iterate on them to see which one is the one you need?

Lucero
Thanks all.A pre-pared map does seems like the only way to go.I assumed reflection would be useful in this regard, but nothing seemed to return what I want. Out of interest, what would the reflection solution be? Was there a function I missed?
Something like this (but note that the membery may have to be internal or protected in order to show up in the reflected code):typeof(YourClass).GetFields(BindingFlags.Instane|BindingFlags.NonPublic|BindingFlags.Public);
Lucero
A: 

Well, like the posts above mentioned, Reflection is generally a bad idea.

this.GetType().GetMember(senderName) == null;

Would probably work here though.

MiffTheFox