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操作,所以也没有直接调用。
  • 相关阅读:
    java课堂作业(四)
    java听课笔记(五)
    rsync 无密码传输文件
    HTTP返回码总结 (zz)
    打印1到最大的n位数
    两个栈模拟队列
    合并有序数组
    vim MiniBufExplorer 插件
    crontab 定时任务格式
    JNI调用测试
  • 原文地址:https://www.cnblogs.com/hongjiumu/p/2846944.html
Copyright © 2011-2022 走看看