Remove Event Handler via Reflection

  

            // define the binding flags for reflection
            var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

            Type type = target.GetType();
            var fieldInfo = type.GetField("EventName", bindingFlags);
            if (fieldInfo != null)
            {
                // using GetValue() to get the reference of event delegate
                var del = fieldInfo.GetValue(target) as Delegate;
                if (del != null)
                {
                    var eventInfo = type.GetEvent("EventName", bindingFlags);
                    if (eventInfo != null)
                    {
                        // detach the event handler
                        eventInfo.RemoveEventHandler(sender, del);
                    }
                }
            }

 

posted @ 2015-07-17 15:04  悠哉游哉  阅读(245)  评论(0编辑  收藏  举报