如何:在派生类中引发基类事件

如何:在派生类中引发基类事件
http://msdn.microsoft.com/zh-cn/library/vstudio/hy3sefw3.aspx
不要在基类中声明虚拟事件,也不要在派生类中重写这些事件。 C# 编译器无法正确处理这些事件,并且无法预知的该派生的事件的用户是否真正订阅了基类事件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    public class Base
    {
        public delegate void Handelr();
        public event Handelr OnHandle;
 
        public Base()
        {
            OnHandle+=Test;
        }
 
        protected virtual void CallEvent()
        {
            if(OnHandle!=null)
                OnHandle();
        }
 
        public void TestEvent()
        {
            CallEvent();
        }
 
        private void Test()
        {
            Console.WriteLine("I am Test() in Base");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    public class Child:Base
    {
        public Child()
        {
            OnHandle += ChildTest;
        }
 
        protected override void CallEvent()
        {
            //if(OnHandle!=null)
                base.CallEvent();
        }
 
        private void ChildTest()
        {
            Console.WriteLine("I am ChildTest() in Child.");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Child vChild = new Child();
            vChild.TestEvent();
            Console.WriteLine("Over");
            Console.Read();
        }
    }
}

显示结果:
I am Test() in Base
I am ChildTest() in Child.
Over

说白了,基类事件在继承类中没有get操作,所以也没有直接调用。

 

转载于:https://www.cnblogs.com/hongjiumu/archive/2013/01/06/2846944.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值