关于子类中不能调用基类中定义的事件问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public event EventHandler evt;


        static void Main(string[] args)
        {
            Program p = new Program();
            
            p.run();
            Console.Read();
        }

        public void run() {
            evt+=new EventHandler(Method2);
            evt(null,null);
        }

        public void Method2(object sender, EventArgs e) {
            Console.Write("1");
        }
    }

    class p : Program
    {
        public p() : base() {
            evt += new EventHandler(ss);
            evt(null, null);//此处会出现Error   The event 'ConsoleApplication1.Program.evt' can only appear on the left hand side of += or -= //(except when used from within the type 'ConsoleApplication1.Program') 

        }

        public void ss(object sender, EventArgs e)
        { }
    }

}

     你要想在派生类中触发基类中的事件,直接去调用基类中的事件,这是不允许的。 

     如果需要在派生类中去触发事件,则可以在基类中提供触发事件的protected virtual方法,想触发事件时就在派生类中调用这个方法,在派生类在要处理这个事件时,可以不用+=来附加事件处理方法,可以直接重写基类中的这个方法(注意:派生类要用base调用基类中的方法,否则使用+= 附加的事件处理方法不会得到调用)。 

     如果一定要在在派生类中直接去触发的事件,那么把event关键字去掉就可以实现。应为事件是一种特殊的委托,事件的处理实际上是使用委托调用相应的方法去执行相应的操作。加与不加event关键字,对编译结果完全没有影响。

event关键字的作用 

      加了event关键字,那么在类的外部 只允许+=与-=操作,而其它操作是不允许的。这也是为什么会得到那个编译错误原因。这是为了防止发生诸如在类的外部执行=操作,从而导致原来附加的 方法被覆盖掉!

原文地址:https://www.cnblogs.com/kangyi/p/1467477.html