using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public delegate T Function<out T>(); //泛型委托 out关键字:基于协变的变体 //public delegate Strong Function2(); //普通委托 public delegate void Operate<in T>(T instance);//泛型委托 in关键字:基于逆变的变体 public class Program { static void Main(string[] args) { ////协变委托 //Function<Strong> funStrong = new Function<Strong>(GetInstance); //Function<Weak> funWeak = funStrong; //Weak weak = funWeak(); ////逆变委托 //Operate<Weak> opWeak = new Operate<Weak>(DoSth); //Operate<Strong> opStrong = opWeak; //opStrong(new Strong()); //Func<Students, Student> f = new Func<Students, Student>(GetStudent); Students ss = new Students(); ss.stus.Where(a => a.name == ""); var c = ss.MySelect(a => a.MySelect2(b => b.name == "wushuangqi")); Console.WriteLine(c.id); Console.WriteLine(1.oper(2, add)); Console.WriteLine(2.oper(1, (a, b) => a - b)); } static int add(int a,int b) { return a + b; } static Student GetStudent(Students ss) { return new Student(); } static Strong GetInstance() { return new Strong(); } static void DoSth(Weak weak) { //... } } /// <summary> /// 强类型 /// </summary> class Weak { } /// <summary> /// 弱类型 /// </summary> class Strong : Weak { } class Student { public string name { get; set; } public string id { get; set; } } class Students { public Students() { stus = new List<Student>(); stus.Add(new Student { name = "wushuangqi", id = "1" }); stus.Add(new Student { name = "wushuangqi", id = "2" }); stus.Add(new Student { name = "lingyuan", id = "2" }); } public List<Student> stus { get; set; } } static class MyHelp { public static Student MySelect(this Students ss, Func<List<Student>, Student> func) { //Student s = null; //func() return func(ss.stus); //return s; //return new Student(); } public static Student MySelect2(this List<Student> sss, Func<Student, bool> func) { Student s = null; foreach (var item in sss) { if (func(item)) { s = item; break; } } return s; //return new Student(); } //public Student ddd(Students ss) //{ // foreach (Student s in ss.stus) // { // if (s.name.Equals("wushuangqi")) // { // return s; // } // else // { // return null; // } // } // return null; //} public static int oper(this int a, int b, mydg dg) { return dg(a, b); } } public delegate int mydg(int a, int b); }