泛型 Generic

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

namespace MyGeneric.CC
{
    /// <summary>
    /// 只能放在接口或者委托的泛型参数前面
    /// out 协变covariant    修饰返回值 
    /// in  逆变contravariant  修饰传入参数
    /// </summary>
    public class CCTest
    {
        public static void Show()
        {
            {
                Bird bird1 = new Bird();
                Bird bird2 = new Sparrow();
                Sparrow sparrow1 = new Sparrow();
                //sparrow sparrow2 = new bird();
            }


            {
                List<Bird> birdList1 = new List<Bird>();
                //List<Bird> birdList2 = new List<Sparrow>();//两个list泛型实例不存在继承关系

                List<Bird> birdList3 = new List<Sparrow>().Select(c => (Bird)c).ToList();
            }
            {
                IEnumerable<Bird> birdList1 = new List<Bird>();

                IEnumerable<Bird> birdList2 = new List<Sparrow>();
                //Action<int>
                //Func<int,string,int,string>
            }


            {
                ICustomerListOut<Bird> customerList1 = new CustomerListOut<Bird>();

                ICustomerListOut<Bird> customerList2 = new CustomerListOut<Sparrow>();
            }



            {
                ICustomerListIn<Sparrow> customerList2 = new CustomerListIn<Sparrow>();
                ICustomerListIn<Sparrow> customerList1 = new CustomerListIn<Bird>();

                ICustomerListIn<Bird> birdList1 = new CustomerListIn<Bird>();
                birdList1.Show(new Sparrow());
                birdList1.Show(new Bird());

            }


            {
                IMyList<Sparrow, Bird> myList1 = new MyList<Sparrow, Bird>();
                IMyList<Sparrow, Bird> myList2 = new MyList<Sparrow, Sparrow>();//协变
                IMyList<Sparrow, Bird> myList3 = new MyList<Bird, Bird>();//逆变
                IMyList<Sparrow, Bird> myList4 = new MyList<Bird, Sparrow>();//协变+逆变
            }
        }
    }

    public class Bird
    {
        public int Id { get; set; }
    }
    public class Sparrow : Bird
    {
        public string Name { get; set; }
    }

    public interface ICustomerListIn<in T>
    {
        //T Get();

        void Show(T t);
    }

    public class CustomerListIn<T> : ICustomerListIn<T>
    {
        //public T Get()
        //{
        //    return default(T);
        //}

        public void Show(T t)
        {
        }
    }

    /// <summary>
    /// out 协变 只能是返回结果
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface ICustomerListOut<out T>
    {
        T Get();

        //void Show(T t);
    }

    public class CustomerListOut<T> : ICustomerListOut<T>
    {
        public T Get()
        {
            return default(T);
        }

        //public void Show(T t)
        //{

        //}
    }





    public interface IMyList<in inT, out outT>
    {
        void Show(inT t);
        outT Get();
        outT Do(inT t);

        ////out 只能是返回值   in只能是参数
        //void Show1(outT t);
        //inT Get1();

    }

    public class MyList<T1, T2> : IMyList<T1, T2>
    {

        public void Show(T1 t)
        {
            Console.WriteLine(t.GetType().Name);
        }

        public T2 Get()
        {
            Console.WriteLine(typeof(T2).Name);
            return default(T2);
        }

        public T2 Do(T1 t)
        {
            Console.WriteLine(t.GetType().Name);
            Console.WriteLine(typeof(T2).Name);
            return default(T2);
        }
    }

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

namespace MyGeneric
{
    public class Constraint
    {
        /// <summary>
        /// 泛型约束,基类约束:
        /// 1 在泛型方法内可以直接使用基类的属性和方法
        /// 2 调用的时候,只能传递基类或者基类的子类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tParameter"></param>
        public static void Show<T>(T tParameter) where T : People, IWork
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString());
            //((People)tParameter).Id
            //tParameter.
            Console.WriteLine("id={0} name={1}", tParameter.Id, tParameter.Name);
            tParameter.Hi();

            tParameter.Work();
            //tParameter.Id
            //tParameter.Name
        }


        private void Linq()
        {
            
        }



        public static void ShowPeople(People tParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString());
            //((People)tParameter).Id
            //tParameter.
            Console.WriteLine("id={0} name={1}", tParameter.Id, tParameter.Name);
            tParameter.Hi();

            //tParameter.Work();
            //tParameter.Id
            //tParameter.Name
        }


        public static void ShowInterface<T>(T tParameter) where T : ISports
        {

            tParameter.Pingpang();
        }
        public static T Get<T>(T tParameter)
        //where T : new()//无参数构造
        //where T : class//引用类型
        //where T : struct//值类型
        {
            //T t = new T();
            //return t;

            //return null;

            return default(T);
            //return tParameter;
        }

        /// <summary>
        /// 多重约束,,是而且的关系 and
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void Many<T>() where T : class, ISports, IWork, new()
        {


        }

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

namespace MyGeneric
{
    public class GenericClass<T>
    {

        public void Show(T t)
        {
            Console.WriteLine(t);
        }

        public void GenericMethod<W, X, Y, Z, Yoyo, Eleven>()
        { }

        public T Get(T t)
        {
            List<int> iList = null;
            return t;
        }
    }

    public interface IGet<T>
    { }

    public delegate void GetHandler<T>();


    public class ChildClass : GenericClass<int>, IGet<string>
    {

    }

    public class ChildClass<T, W> : GenericClass<T>, IGet<W>
    {
        private Child child = new Child();
    }


    public class Parent
    {
        public Parent(string name)
        { }
    }

    public class Child : Parent
    {
        public Child():base("123")
        { }
    }

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

namespace MyGeneric
{
    public class GenericMethod
    {
        /// <summary>
        /// 延迟声明:把参数类型的声明推迟到调用
        /// 不是语法糖,而是由框架升级提供的功能
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tParameter"></param>
        public static void Show<T>(T tParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString());
        }


        /// <summary>
        /// 打印个object值
        /// 1 任何父类出现的地方,都可以使用子类来替换
        /// 2 object是一切类型的父类
        /// </summary>
        /// <param name="oParameter"></param>
        public static void ShowObject(object oParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(GenericMethod), oParameter.GetType().Name, oParameter);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyGeneric
{
    /// <summary>
    /// 1 引入泛型:延迟声明
    /// 2 如何声明和使用泛型
    /// 3 泛型的好处和原理
    /// 4 泛型类、泛型方法、泛型接口、泛型委托
    /// 5 泛型约束
    /// 6 协变 逆变(选修)
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //var list = new List<int>() { 1, 2, 3, 4 }
                //.Select(i => new
                //{
                //    id = i,
                //    name = "Test" + i
                //});
                //foreach (var item in list)
                //{
                //    Console.WriteLine(item.id);
                //    Console.WriteLine(item.name);
                //}

                //List<int>


                Console.WriteLine("============================今天是泛型Generic课程=================================");
                int iValue = 123;
                string sValue = "456";
                DateTime dtValue = DateTime.Now;
                object oValue = new object();



                Console.WriteLine(typeof(List<int>));
                Console.WriteLine(typeof(Dictionary<int, string>));
                Console.WriteLine("**************************");
                CommonMethod.ShowInt(iValue);
                //CommonMethod.ShowInt(sValue);
                CommonMethod.ShowString(sValue);
                CommonMethod.ShowDateTime(dtValue);

                Console.WriteLine("**************************");
                CommonMethod.ShowObject(oValue);

                CommonMethod.ShowObject(iValue);
                CommonMethod.ShowObject(sValue);
                CommonMethod.ShowObject(dtValue);

                Console.WriteLine("**************************");
                GenericMethod.Show<object>(oValue);
                GenericMethod.Show<int>(iValue);
                GenericMethod.Show(iValue);//类型参数可以省略,由编译器推断出来
                //GenericMethod.Show<int>(sValue);//类型参数和参数必须匹配
                GenericMethod.Show<string>(sValue);
                GenericMethod.Show<DateTime>(dtValue);

                Console.WriteLine("**************************");
                People people = new People()
                {
                    Id = 11,
                    Name = "山冈"
                };
                Japanese japanese = new Japanese()
                {
                    Id = 112,
                    Name = "鬼子"
                };

                Chinese chinese = new Chinese()
                {
                    Id = 123,
                    Name = "口口"
                };
                Hubei hubei = new Hubei()
                {
                    Id = 123,
                    Name = "pig猪"
                };


                //Constraint.Show<People>(people);
                Constraint.Show<Chinese>(chinese);
                Constraint.Show<Hubei>(hubei);

                Constraint.ShowPeople(people);
                Constraint.ShowPeople(chinese);
                Constraint.ShowPeople(hubei);


                //Constraint.ShowInterface<People>(people);//没有实现ISports接口
                Constraint.ShowInterface<Chinese>(chinese);
                Constraint.ShowInterface<Hubei>(hubei);

                Constraint.ShowInterface<Japanese>(japanese);

                //Constraint.Show<Japanese>(japanese);//虽然Japanese有ID和Name,但是因为不是People,所以不能调用

                //Constraint.Show<int>(iValue);//约束后,只能按约束传递

                #region Monitor
                {
                    long commonTime = 0;
                    long objectTime = 0;
                    long genericTime = 0;
                    {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        for (int i = 0; i < 1000000000; i++)
                        {
                            ShowCommon(iValue);
                        }
                        stopwatch.Stop();
                        commonTime = stopwatch.ElapsedMilliseconds;
                    }
                    {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        for (int i = 0; i < 1000000000; i++)
                        {
                            ShowObject(iValue);
                        }
                        stopwatch.Stop();
                        objectTime = stopwatch.ElapsedMilliseconds;
                    }
                    {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        for (int i = 0; i < 1000000000; i++)
                        {
                            ShowGeneric<int>(iValue);
                        }
                        stopwatch.Stop();
                        genericTime = stopwatch.ElapsedMilliseconds;
                    }
                    Console.WriteLine("commonTime = {0} objectTime = {1} genericTime = {2}", commonTime, objectTime, genericTime);
                }



                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }

        private static void ShowCommon(int iParameter)
        { }
        private static void ShowObject(object oParameter)
        { }
        private static void ShowGeneric<T>(T tParameter)
        { }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyGeneric
{
    public interface ISports
    {
        void Pingpang();
    }

    public interface IWork
    {
        void Work();
    }


    public class People
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public void Hi()
        { }

    }

    public class Chinese : People, ISports, IWork
    {
        public string Tradition { get; set; }

        public void SayHi()
        {
            Console.WriteLine("吃了么?");
        }

        public void Pingpang()
        {
            Console.WriteLine("打乒乓球...");
        }

        public void Work()
        {
            throw new NotImplementedException();
        }
    }

    public class Hubei : Chinese
    {
        public string Changjiang { get; set; }
        public void Majiang()
        {
            Console.WriteLine("打麻将啦。。");
        }
    }


    public class Japanese : ISports
    {
        public int Id { get; set; }
        public string Name { get; set; }


        public void Pingpang()
        {
            Console.WriteLine("打乒乓球...");
        }
    }
}
原文地址:https://www.cnblogs.com/zhengqian/p/8490548.html