使用代码删除事件处理程序
可以使用按钮单击事件中的以下代码删除事件处理程序。
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += (o, x) =>
{
Button b = o as Button;
FieldInfo eventclick = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
object eventValue = eventclick.GetValue(b);
PropertyInfo events = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList eventHandlerList = (EventHandlerList)events.GetValue(b, null);
eventHandlerList .RemoveHandler(eventValue, eventHandlerList [eventValue]);
MessageBox.Show("Test");
};
但我想从 vgridcontrols CellValueChanged 事件中删除事件处理程序。下面我必须为“EventClick”写什么?
FieldInfo eventclick = typeof(Control).GetField(
"EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
An event handler can be removed with the following code in the button click event.
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += (o, x) =>
{
Button b = o as Button;
FieldInfo eventclick = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
object eventValue = eventclick.GetValue(b);
PropertyInfo events = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList eventHandlerList = (EventHandlerList)events.GetValue(b, null);
eventHandlerList .RemoveHandler(eventValue, eventHandlerList [eventValue]);
MessageBox.Show("Test");
};
But I want to remove the event handler from the vgridcontrols CellValueChanged event. What do I have to write for "EventClick" in the following?
FieldInfo eventclick = typeof(Control).GetField(
"EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(2)
您不能可靠从事件中删除事件处理程序,除非您已经有一个可以以正常方式与
-=
一起使用的“同等”委托。通过反射获取字段并对其进行修改显然违反了封装性并且会使您的代码变得极其脆弱。我强烈建议不要这样做。
目前尚不清楚“vgridcontrols”(
DataGridView
?)是什么意思,但无论您提出什么解决方案都必定是特定于实现的 - 并且该实现可以轻松地随着下一个版本的变化而改变。相反,花时间提出一种设计,要么根本不需要删除事件处理程序,要么保留对处理程序的引用并可以以正常方式删除它。
You cannot reliably remove an event handler from an event unless you already have an "equal" delegate you can use with
-=
in the normal way.Getting fields with reflection and hacking around at them is a clear violation of encapsulation and makes your code extremely fragile. I would strongly recommend against doing it.
It's not clear what you mean by "vgridcontrols" (
DataGridView
?) but whatever solution you come up with is bound to be implementation-specific - and that implementation could easily change with the next version of whatever it is.Instead, put time into coming up with a design where either you don't need to remove the event handler at all, or you keep a reference to the handler and can remove it in the normal way.
这是 VB.NET,但您可以轻松地将其修改为 C#。这就是你想要的:
This is VB.NET, but you can modify it easily to C#. This is what you want: