Is there a开发者_JS百科nyway 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.
}
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.
Yes, you should be able to do this with the reflection APIs.
That's all you wanted to know, right? :)
精彩评论