Add event handler dynamically having the delegate name in a string(在字符串中动态添加具有委托名称的事件处理程序)
问题描述
我需要给一个对象分配一个eventHandler,这样:
I need to assign an eventHandler to an object, in this way:
_Element.AddHandler(UIElement.MouseLeftButtonUpEvent,
new RoutedEventHandler(Vars.Digit), true);
但事实上,我在 Vars 对象实例中只有一个包含Digit"或其他方法名称的字符串.
but, in fact, I only have a string that contains "Digit" or other method name in the Vars object instance.
是否可以使用反射或其他技巧来实现这一点?
It is possible to achieve this using reflection or other kind of trick?
谢谢.
推荐答案
是的,你可以找到 Type.GetMethod,以及带有 Type.GetEvent,然后使用 EventInfo.AddEventHandler.这可能有点繁琐——而且会有很多地方可以进行错误处理——但应该不会太难.如果您希望能够绑定非公共方法/事件,请不要忘记指定绑定标志.
Yes, you can find the method with Type.GetMethod, and the event with Type.GetEvent, then add a handler with EventInfo.AddEventHandler. It may be slightly fiddly - and there'll be a lot of places to put error handling - but it shouldn't be too hard. Don't forget to specify binding flags if you want to be able to bind non-public methods/events.
这篇关于在字符串中动态添加具有委托名称的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在字符串中动态添加具有委托名称的事件处理程序
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
