委托的协变和逆变

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

namespace demo3
{
    class Program
    {
       
        static void Main(string[] args)
        {
            //协变看返回类型,允许返回子类,如委托返回类型是Animal,方法的类型可以允许返回Person
            Test.sayDeltegate t1= new Test.sayDeltegate(Test.say); //协变
            Test.sayDeltegate t2 = new Test.sayDeltegate(Test.say1);//协变

            //逆变看参数,允许父类当作子类使用,如委托的签名是(Person per),那么方法可以是(Animal a)
            Test.sayWhatDeltegate t3 = Test.saywhat;//逆变

        }
    }

    public class Animal { 
    
    }

    public class Person : Animal { 
    
    }
    public class Test
    {
        public delegate Animal sayDeltegate();
        public delegate string sayWhatDeltegate(Person a);
        public static Animal say()
        {
            return null;
        }

        public static Person say1()
        {
            return null;
        }
        public static string saywhat(Animal animal)
        {
            return null;
        }
    }




}
原文地址:https://www.cnblogs.com/tiancai/p/6396975.html