C#事件去除语法 [英] C# event removal syntax

查看:150
本文介绍了C#事件去除语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的语法在C#中删除事件处理程序混淆

I am confused by the syntax for removing event handlers in C#.

Something += new MyHandler(HandleSomething); // add
Something -= new MyHandler(HandleSomething); // remove



新创建每行一个新的对象,所以你添加一个对象
,然后要求它删除不同的对象。

The "new" creates a new object on each line, so you add one object and then ask it to remove a different object.

什么是真的在幕后,这可以工作?结果
它肯定,是不是从语法明显

What is really going on under the covers that this can work?
It sure isn't obvious from the syntax.

推荐答案

在+ =和 - =是内置的内部方法命名语法快捷方式添加()和删除(),它添加或删除指向代表该委托具有作为一个私人领域的内部链接列表。当您运行删除,它开始在链表的头,一次检查列表中的一个每位代表,直到它找到一个等于给你传递给remove()方法之一。 (使用 - =语法)

The += and the -= are syntax shortcuts for built-in internal methods named Add(), and Remove(), which add or remove a pointer to an internal linked list of delegates that the delegate has as a private field. When you run Remove, it starts at the head of the linked list and examines each delegate in the list one at a time until it finds one that is "equal" to the one you passed to the Remove() method. ( using -= syntax)

然后,它会删除一个从链表和补丁链表保留它的连接...

Then, it removes that one from the linked list, and patches the linked list to retain it's connectivity...

在这种情况下,等于方法(为一个代表())被覆盖,以便它只比较委托的目标,和methodPtr,这将是相同的,即使你已经创建了一个新的委托传递给删除...

In this context, the 'equals' method (for a delegate()) is overridden so that it only compares the target of the delegate, and the methodPtr, which will be the same even though you have created a new delegate to pass to Remove...

这篇关于C#事件去除语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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