• C#


    百度百科逆变的概念,再来练下对逆变的理解。

    在下面的示例代码中,定义三个委托方法,一个普通方法  

    委托方法的签名参数继承于Human,普通方法的参数是父类。

    因此,在调用委托时,可把子类转换为父类。

    这样可以使我们的普通方法更具通用性。

    using System;

    namespace ConsoleApp1

    {

    class Human { }

    class Student : Human { }

    class Teacher : Human { }

    class Program

    {

    public delegate void StudentDelegate(Student stu);

    public delegate void TeacherDelegate(Teacher tea);

    public delegate void HumanDelegate(Human h);

    public static void TestHandler(Human human)

    {

    Console.WriteLine("This is class :{0}", human.GetType());

    }

    public static void StudentHandler(Student human)

    {

    Console.WriteLine("This is class :{0}", human.GetType());

    }

    static void Main(string[] args)

    {

    Console.WriteLine("input any key to start.");

    Console.Read();

    StudentDelegate handler1 = TestHandler;

    TeacherDelegate handler2 = TestHandler;

    HumanDelegate handler3 = TestHandler;

    handler1.Invoke(new Student());

    handler2.Invoke(new Teacher());

    handler3.Invoke(new Human());

    Console.Read();

    }

    }

    }

  • 相关阅读:
    51nod 1031+斐波那契和杨辉三角的一些基础知识
    51nod 1297
    萌新二叉树学习笔记
    HDU3415【单调队列】
    萌新瞎讲网络流之最大流【不定期更新理解篇】
    萌新浅谈单调队列
    51nod 1021【区间DP】
    51nod 1278【贪心】
    51nod 1413
    51nod1181【素数筛】
  • 原文地址:https://www.cnblogs.com/tcli/p/6661803.html
Copyright © 2020-2023  润新知