Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c# - Solution to remove Event handler dynamically (using reflection). Is there a better way to do this?

I had the need to remove event handlers from a control loaded from a dll that I don't have the code for. Since there doesn't seem to be an 'official' (i.e. supported by public methods of the .NET Framework), I was was able to create a couple extension methods that did exactly that using Reflection.

See this blog post for all the details: Removing an Event from a WinForm ListView control using reflection

Here is a code sample of how to remove the SelectedIndexChanged event (dynamically and without access to the original handler)

//for a UserControl (in fact any control that implements System.ComponentModel.Component)
var userControl = new UserControl();
//we can get the current mapped event handlers
userControl.eventHandlers();
//its signature
userControl.eventHandlers_MethodSignatures();
//remove one by using the static field name
userControl.remove_EventHandler("EVENT_SELECTEDINDEXCHANGED");
//or use this one specifically mapped to the SelectedIndexChanged event
userControl.remove_Event_SelectedIndexChanged

My question is: "is there another way?"

Although my solution works and seems stable, I'm doing internal .NET objects manipulation, so maybe there is a better solution (in 4.0 or 4.5)?

Related posts:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...