C#汇总-泛型

版权声明:未经本人允许,必须声明原文转载地址和作者! https://blog.csdn.net/liuchang19950703/article/details/85215089

一:C#泛型类,泛型方法,泛型接口,泛型委托

二:C#泛型约束

三:C#泛型协变,逆变,泛型缓存

 1:定义一个泛型demo类

/// <summary>
    /// 泛型类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="L"></typeparam>
    /// <typeparam name="M"></typeparam>
    public class GenericClass<T, K, L, M>
        where T : class //引用类型约束
        where K : ElectriThing, //基类约束
                         new()           //无参数构造函数约束
        where L : struct          //值类型约束
        where M : IPhone  //接口约束
    {

        public GenericClass()
        { 
        
        }
        //<summary>
        //泛型类里面的泛型字段
        //</summary>
        private K _K;
        public GenericClass(K xK)
        {
            string desc = xK.Description;
        }

        /// <summary>
        /// 泛型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputStr"></param>
        public void DoThing(T inputStr)
        {
            Console.WriteLine(inputStr);
        }
    }

    //<summary>
    //泛型接口
    //</summary>
    //<typeparam name="T"></typeparam>
    public interface IGenericface<T>
    {
        T IGetMsg(T xT);
    }

 2:定义一个泛型Electrithing(电子产品)类

  public class ElectriThing
    { 
        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; }
        public void UseEle()
        {
            Console.WriteLine("电子产品要用电!");
        }
    }

 3:定义一个泛型手机类

  public class Phone : ElectriThing
    {
        /// <summary>
        /// 品牌
        /// </summary>
        public string Brand { get; set; }

        public void Call()
        {
            Console.WriteLine("手机可以带电话!");
        }
    }

    /// <summary>
    /// 电话接口
    /// </summary>
    public interface IPhone
    {
        void PlayGame();

    }

4:调用类运行

public class Program
    {
        public static void Main(string[] args)
        {

            Phone iPhone = new Phone();
            //对应四个参数
            GenericClass<Phone, ElectriThing, int, IPhone> GenericClass = new GenericClass<Phone, ElectriThing, int, IPhone>();
            //方法1转变
            List<ElectriThing> electriList = new List<Phone>() { }.Select(a => (ElectriThing)a).ToList();
            //方法2转变-利用泛型协变
            IEnumerable<ElectriThing> iElectriList = new List<Phone>() { 
                  new Phone(){
                  Description="插上电使用",
                  Brand="魅族16X"
                  }
            };
            electriList = iElectriList.ToList();
            string Description = electriList.Find(a => a.Description == "插上电使用").Description;
            Console.WriteLine(Description);
            Console.ReadLine();
        }
    }

猜你喜欢

转载自blog.csdn.net/liuchang19950703/article/details/85215089
今日推荐