zoukankan      html  css  js  c++  java
  • 如何:在派生类中引发基类事件

    如何:在派生类中引发基类事件
    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操作,所以也没有直接调用。
  • 相关阅读:
    记录一次电话面试
    记录一次git合并
    HTML通用属性与常见标签
    位运算的应用
    HTML总结
    前端MVC
    常用软件
    docker常用命令
    composer install(update)时出现killed
    优化小技巧:该怎么识别百度蜘蛛呢
  • 原文地址:https://www.cnblogs.com/hongjiumu/p/2846944.html
Copyright © 2011-2022 走看看