views:

18

answers:

2

Is there anyway in C# to call a method based on a Enum and/or class? Say if I were to call

Controller<Actions.OnEdit, Customer>(customer);

Could I do something like this then?

public void Controller<TAction, TParam>(TParam object)
{
    Action<TParam> action = FindLocalMethodName(TAction);
    action(object);
}

private Action<T> FindLocalMethodName(Enum method)
{
    //Use reflection to find a metode with 
    //the name corresponding to method.ToString()
    //which accepts a parameters type T.
}
A: 

Yes, you should be able to do this with the reflection APIs.

That's all you wanted to know, right? :)

Daniel Plaisted
+2  A: 

This should do it. Assume obj is the object you want to call the method on...

var methodInfo = ( from m in obj.GetType().GetMethods()
                   where m.Name == method.ToString() && 
                         m.ReturnType == typeof(void)
                   let p = m.GetParameters()
                   where p.Length == 1 && 
                         p[0].ParameterType.IsAssignableFrom(typeof(T))
                   select m ).FirstOrDefault();

return (Action<T>)Delegate.CreateDelegate(typeof(Action<T>), obj, methodInfo);

Note that the method has to be public or as accessible to the reflecting code as it would be without reflection because Silverlight has very limited reflection of non-public methods.

Josh Einstein
It's fine for the method to be public, i just don't want to have to clutter my viewmodel, the less lines of code i write, the less mistakes i would make, the faster i can get things done right?
cmaduro
Totally agree. I used this technique to expose ICommands from my ViewModel without the clutter of command properties. I just looked for a CommandAttribute on the method and stuck a DelegateCommand in a Commands dictionary.
Josh Einstein