为什么我无法访问属于其他类型成员的事件的成员?

And*_*are 4 c# events delegates

注意:这是受WebBrowser Event Properties的启发

为什么我能够MulticastDelegate在声明事件但不在其外的类型中访问事件的成员?

例如:

using System;

class Bar
{
    public static event Action evt;
}

class Program
{
    static event Action foo;
    static Bar bar;

    static void Main()
    {
        // this works
        Delegate[] first = foo.GetInvocationList();

        // This does not compile and generates the following
        // error:
        //
        // The event 'Bar.evt' can only appear on the 
        // left hand side of += or -= (except when used 
        // from within the type 'Bar')
        Delegate[] second = bar.evt.GetInvocationList();
    }
}
Run Code Online (Sandbox Code Playgroud)

我觉得这很简单,我没有看到.

Jon*_*eet 6

事件不会公开字段及其值 - 它只是公开订阅方法和取消订阅方法,其方式与属性如何公开getter和setter的方式类似.

从类外,可以用一个事件做的是订阅,或取消订阅.这就是它的目的 - 用于封装.

有关更多信息,请参阅我的活动文章