具有自定义事件访问器的C#事件(添加和删除) [英] C# events with custom event accessor (add and remove)

查看:70
本文介绍了具有自定义事件访问器的C#事件(添加和删除)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释自定义事件访问器的工作原理吗?我已经在Google上阅读了几篇文章,但仍然听不懂.还有,什么时候使用它?

Can someone explain to me how custom event accessor works? I have read a couple of articles on google but still could not understand. Also, when to use it?

我的项目中有以下代码片段.如果有人可以向我解释这一点,那就太好了.

I have the following code snippet from my project. If someone can explain this to me it would be really great.

private event Action<int> ActivityChanged = delegate {};

event Action<int> IActivityFacade.ActivityChanged
{
    add
    {
        ActivityChanged += value;
        value(GetSelectedActivity()); 
    }
    remove { ActivityChanged -= value; }
}

推荐答案

在不完全了解现有文档和其他有关自定义事件访问器的参考文献中,特定地是您所不了解的,不可能确定地知道您要寻找什么答案.

Without knowing exactly what part of the existing documentation and other references regarding custom event accessors it is specifically that you don't understand, it's impossible to know for sure what answer you're looking for.

AC# event 只是一个 add remove 方法(类似于属性的 get set 方法).编译器为这些方法提供默认实现,但是如果您要自定义行为,则可以自己编写这些方法.在您的示例中,它并不是线程安全的,显然,自定义访问器在那里,因此,一旦添加了新订阅的委托,便会立即调用它.

A C# event is simply an add and a remove method (similar to a property's get and set methods). The compiler provides a default implementation for these methods, but if you have custom behavior you want to implement yourself, you can write the methods yourself. In your example, which is not thread-safe by the way, the custom accessors are apparently there so that a newly subscribed delegate is invoked as soon as it's added.

如果您需要更多详细信息,请改进此问题,以使您可以轻松了解自定义事件访问器的具体含义.请务必准确解释您所做的以及您已经参考的文档,以便我们避免冗长的答案,这些答案浪费时间在您已经了解的方面.

If you need more details than that, please improve the question so that it's clear what it is specifically about custom event accessors that you are having trouble understanding. Be sure to explain exactly what you do understand and what documentation you've already referenced, so that we can avoid excessively long answers that waste time on aspects you already know about.

这篇关于具有自定义事件访问器的C#事件(添加和删除)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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