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

时间:2009-05-11 16:50:40

标签: 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();
    }
}

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

1 个答案:

答案 0 :(得分:6)

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

从课程外部,您可以对事件进行所有订阅或取消订阅。这是它的目的 - 用于封装。

有关详细信息,请参阅我的event article