泛型委托示例

delegate T Factory<out R, in S , T>() 

//   out R  协变        in  S   逆变     T   不变

 

----------------------------------------------------------------------------------------------------

public delegate TR Func<T1, T2, TR>(T1 p1, T2 p2);   //泛型委托  TR委托返回类型   T1,T2 委托参数类型

class Simple

{

  static public string PrintString(int p1, int p2) //方法匹配委托

  {

    int total = p1 + p2;

    return total.ToString();

  }

}

class Program

{

  static void Main()

    {

      var myDel = new Func <int, int, string>(Simple.PrintString);   //创建委托实例

      Console.WriteLine("ToTal: {0}", myDel(15, 13));//  调用委托

    }

}

 

另一种out协变

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

namespace ConsoleApplication33
{
    class Animal                                            //基类
    {
        public int Legs = 4;
    }

    class Dog:Animal                                        //派生类
    {

    }

    class Program
    {
        delegate T Factory<out T>();

        static Dog MackDog() { return new Dog(); }
        static void Main(string[] args)
        {
            Factory<Animal> animalMacker = MackDog;             //隐式强制转换

            Factory<Dog> dogMacker = MackDog;

            Factory<Animal> animalMacker2 = dogMacker;          //需要out标识符

            Factory<Animal> animalMacker3 = new Factory<Dog>(MackDog);  //需要out标识符
        }
    }
}

 

 

posted @ 2019-11-24 10:32  八风不动  阅读(111)  评论(0编辑  收藏  举报