c#中的event关键字

这段代码取自stackoverflow:

   

using System;
class Akann
{
    static void Main(string[] args)
    {
        var a = new A();
        a.eventOne += (s, e) => Console.WriteLine("One");
        a.eventTwo += (s, e) => Console.WriteLine("Two");
        a.RaiseOne();
        a.RaiseTwo();
        a.eventOne(null, EventArgs.Empty);//这句将不能被编译
        a.eventTwo(null, EventArgs.Empty);
    }

}

class A {
    public event EventHandler eventOne;
    public EventHandler eventTwo;

    public void RaiseOne()
    {
        if (eventOne != null)
            eventOne(this, EventArgs.Empty);
    }

    public void RaiseTwo()
    {
        if (eventTwo != null)
            eventTwo(this, EventArgs.Empty);
    }
}

当你编译后,编译器出现错误提示:

error CS0070: The event 'A.eventOne' can only appear on the left hand side of += or
-= (except when used from within the type 'A')

什么原因呢?event关键字修饰的类域名义上是public访问修饰符,但在本类外除了使用+=和-=的方法访问外,必须通过另外的本类的公有方法从类外来访问,通过event修饰的域更像一个私有的域,它实际上是一个被私有域支持的公有属性。

当你查看编译后生成IL代码会发现:编译器会给event关键字修饰的域添加add_xxx和remove_xxx方法。在本类外,如果你不为这个event域添加其他public访问方法的话,那么你只能通过这两个方法公有访问这个域。当你使用+=和-=访问这个域时实际上只是使用了这两个方法。

实际上我所了解的使用event和不使用event关键字的区别本质上仅仅只有这么一点,不知道C#为什么只为这么一个特性就设立一个关键字,而且还那么晦涩。

 

   

posted @ 2012-12-15 19:02  Akann  阅读(1064)  评论(0编辑  收藏  举报