添加事件处理程序具有动态字符串中的代表的名字 [英] Add event handler dynamically having the delegate name in a string

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

问题描述

我需要一个EventHandler分配到一个对象,在这种方式:

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

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

但是,事实上,我只有一个包含数字或其他方法名中瓦尔对象实例的字符串。

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天全站免登陆