如何:实现自定义事件访问器(C# 编程指南)How to: Implement Custom Event Accessors (C# Programming Guide)

事件是一种特殊的多播委托,只能从声明它的类中进行调用。An event is a special kind of multicast delegate that can only be invoked from within the class that it is declared in. 客户端代码通过提供对应在引发事件时调用的方法的引用来订阅事件。Client code subscribes to the event by providing a reference to a method that should be invoked when the event is fired. 这些方法通过事件访问器添加到委托的调用列表中,事件访问器类似于属性访问器,不同之处在于事件访问器命名为 addremoveThese methods are added to the delegate's invocation list through event accessors, which resemble property accessors, except that event accessors are named add and remove. 在大多数情况下,无需提供自定义事件访问器。In most cases, you do not have to supply custom event accessors. 如果代码中没有提供自定义事件访问器,编译器将自动添加它们。When no custom event accessors are supplied in your code, the compiler will add them automatically. 但在某些情况下,可能需要提供自定义行为。However, in some cases you may have to provide custom behavior. 主题操作说明:实现接口事件中介绍了这样一种情况。One such case is shown in the topic How to: Implement Interface Events.

示例Example

下面的示例演示如何实现自定义的 add 和 remove 事件访问器。The following example shows how to implement custom add and remove event accessors. 虽然可以替换访问器内的任何代码,但建议先锁定事件,再添加或删除新的事件处理程序方法。Although you can substitute any code inside the accessors, we recommend that you lock the event before you add or remove a new event handler method.

event EventHandler IDrawingObject.OnDraw
{
    add
    {
        lock (objectLock)
        {
            PreDrawEvent += value;
        }
    }
    remove
    {
        lock (objectLock)
        {
            PreDrawEvent -= value;
        }
    }
}

请参阅See also