简体   繁体   English

C#匿名方法/块?

[英]C# anonymous method/block?

I cannot understand this piece of code what is the "ViewDissapearing"? 我不明白这段代码是什么“ ViewDissapearing”? And what about "add" and "remove" blocks? 那么“添加”和“删除”块呢?

public event EventHandler ViewDisappearing;

public event EventHandler ViewDissapearing {
    add {
        ViewDisappearing += value;
    }
    remove {
        ViewDisappearing -= value;
    }
}

This is done to provide two names for the same event. 这样做是为了为同一事件提供两个名称。 "ViewDissapearing" is how the event was previously wrongly named, and all existing code that subscribes to the "ViewDissapearing" event is instead rerouted to subscribe to the new correctly spelt "ViewDisappearing" event instead. “ ViewDissapearing”是先前错误命名事件的方式,订阅了“ ViewDissapearing”事件的所有现有代码都被重新路由以订阅新的拼写正确的“ ViewDisappearing”事件。

The add { ... } block is executed when someone calls ViewDissapearing += ... , which does nothing more than ViewDisappearing += that same ... . 当有人调用ViewDissapearing += ... ,将执行add { ... }块,这只不过ViewDisappearing += that same ...而已。 Similarly for the remove { ... } block and -= . 对于remove { ... }块和-=

This is to allow other code to attach to this event. 这是为了允许其他代码附加到此事件。 This is the same idea as the Get / Set Property of a variable. 这与变量的Get / Set属性相同。 For Events it is Add / Remove. 对于事件,它是添加/删除。 As with Properties of variables, you can use the Variable directly, or you can use an Property. 与变量的属性一样,您可以直接使用变量,也可以使用属性。 You usually use the Properrty if you want to add some custom code when adding a event. 如果要在添加事件时添加一些自定义代码,通常可以使用属性。

这明确说明了编译器通常为类中的事件自动生成的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM