2010-05-21 23 views
1

C#中是否有調用基於枚舉和/或類的方法? 說如果我打電話C# - Silverlight - 動態調用方法

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

我可以這樣做嗎?

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. 
} 

回答

2

這應該做到這一點。假設obj是要呼籲方法的對象...

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); 

注意方法是公共或反射的代碼,因爲這將是沒有反射的訪問,因爲Silverlight的非常有限反映非公開的方法。

+0

這種方法公開很好,我只是不想混亂我的視圖模型,我寫的代碼行數越少,我犯的錯誤就越少,我可以把事情做得更快? – cmaduro 2010-05-22 03:31:15

+0

完全同意。我用這種技術從我的ViewModel中暴露ICommands,沒有命令屬性的混亂。我只是在該方法上查找CommandAttribute,並在Commands字典中粘貼了DelegateCommand。 – Josh 2010-05-22 04:10:58

-1

是的,你應該可以用反射API來做到這一點。

這就是你想知道的,對吧? :)