我可以清除对象中的所有事件和处理程序 [英] Can I clear all events and handler from an object

查看:86
本文介绍了我可以清除对象中的所有事件和处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个组件。我可以清除组件的默认事件和处理程序。

I am using an component. Can I clear component's default events and handler.

推荐答案

您可以删除所有处理程序,但删除事件不仅是不可能的;完全没有任何意义。



每个对象实例都有一些实例成员,其中一些成员是事件实例(让我们留出静态成员,他们是无关紧要,因为你说从一个物体中清除)。 删除它们意味着与删除任何其他成员相同,例如属性名称。对于编译语言,没有这样的东西。



(特别是在事件上,我会告诉你更多:你甚至无法在任何地方的任何事件实例上调用事件除了声明类本身的代码,甚至不是它的派生类。这是一个重要的万无一失的CLR功能,但它让很多人感到困惑。)



-SA
You can remove all handlers, but "remove events" is not just impossible; the whole notion makes no sense at all.

Each object instance has some instance members, and some of those members are event instances (let's set aside static members, they are irrelevant, because you say "clear from an object"). "Removing" them would mean the same as "removing" any other member, such as property "Name". For compiled languages, there is no such thing.

(Specifically on the events, I'll tell you more: you cannot even invoke an event on any event instance anywhere except the code of the declaring class itself, not even its derived class. This is an important fool-proof CLR feature, but it confuses many.)

—SA


是。

试用代码



Yes.
Try the code

private void RemoveClickEvent(Button b)
        {
            FieldInfo f1 = typeof(Control).GetField("EventClick", 
                BindingFlags.Static | BindingFlags.NonPublic);
            object obj = f1.GetValue(b);
            PropertyInfo pi = b.GetType().GetProperty("Events",  
                BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
            list.RemoveHandler(obj, list[obj]);
        }


这篇关于我可以清除对象中的所有事件和处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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