动态地添加事件处理程序名称在字符串中 [英] Add event handler dynamically having the delegate name in a string

查看:141
本文介绍了动态地添加事件处理程序名称在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为一个对象分配一个eventHandler:

I need to assign an eventHandler to an object, in this way:

_Element.AddHandler(UIElement.MouseLeftButtonUpEvent, 
    new RoutedEventHandler(Vars.Digit), true);

但实际上,我只有一个包含Digit或其他方法名称的字符串Vars对象实例。

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.

这篇关于动态地添加事件处理程序名称在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆