33
A
回答
58
// Static method
Action action = (Action) Delegate.CreateDelegate(typeof(Action), method);
// Instance method (on "target")
Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method);
對於Action<T>
等,只是到處指定適當的委託類型。
在.NET中的核心,Delegate.CreateDelegate
不存在,但MethodInfo.CreateDelegate
的作用:
// Static method
Action action = (Action) method.CreateDelegate(typeof(Action));
// Instance method (on "target")
Action action = (Action) method.CreateDelegate(typeof(Action), target);
0
這似乎對約翰的建議基礎上工作過:
public static class GenericDelegateFactory
{
public static object CreateDelegateByParameter(Type parameterType, object target, MethodInfo method) {
var createDelegate = typeof(GenericDelegateFactory).GetMethod("CreateDelegate")
.MakeGenericMethod(parameterType);
var del = createDelegate.Invoke(null, new object[] { target, method });
return del;
}
public static Action<TEvent> CreateDelegate<TEvent>(object target, MethodInfo method)
{
var del = (Action<TEvent>)Delegate.CreateDelegate(typeof(Action<TEvent>), target, method);
return del;
}
}
相關問題
- 1. 從MethodInfo創建委託
- 2. 從MethodInfo構建一個委託?
- 3. 我怎樣才能從行動委託創建一個MethodInfo
- 4. 從methodinfo獲取委託
- 5. 在Mono 2.8.2中創建一個來自methodInfo的委託
- 6. 的MethodInfo和委託
- 7. 如何實現Action委託?
- 8. 根據委託檢查MethodInfo
- 9. Dispatcher.Invoke與Action委託
- 10. 如何從main-viewcontroller創建一個靜態委託?
- 11. C#:我可以將一個顯式委託轉換爲一個Action委託嗎?
- 12. 創建一個屬性setter委託
- 13. C++委託創建
- 14. 鉤一個的MethodInfo到委託字段(字段信息)
- 15. 如何事先不能知道方法簽名時如何從MethodInfo創建委託?
- 16. 如何創建委託實例?
- 17. 如何爲擴展創建委託?
- 18. 如何爲QTreeWidget創建委託?
- 19. 如何與分別創建一個委託
- 20. 如何從Action委託在C#中刪除的方法
- 21. 從System.Type中創建一個通用委託實例
- 22. 未調用UITableView委託方法。從另一個類創建
- 23. 如何從不從EventHandler繼承的委託創建IObservable?
- 24. 使用Ast.Expressions創建委託
- 25. 創建委託事件
- 26. Zizaco委託不創建entrust.php
- 27. 如何從結構的實例方法創建一個開放的委託?
- 28. Parallel.Foreach委託調用另一個委託
- 29. 在一個AppDomain中創建一個委託
- 30. 創建一個委託時,有一個條件屬性
Upvoted。如何將此應用於DataEventArgs? http://ntackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –
2015-10-27 18:57:56
'Delegate.CreateDelegate'似乎在.Net Core中不可用。那裏有任何想法? – IAbstract 2017-05-05 13:41:08
@IAbstract:有趣 - 我沒有發現。您可以改爲調用'MethodInfo.CreateDelegate'。 (剛剛嘗試過,它運行良好。) – 2017-05-05 13:48:51