泛型缓存、静态构造函数、约束

泛型缓存比 字典 效率高好几百倍,因为是jit事先编译好的




/// <summary> /// 每个不同的T都会生成一份不同的副本 /// 适合不同类型,需要缓存一份数据的场景,效率高 /// </summary> /// <typeparam name="T"></typeparam> public class GenericCache<T> { private static string _typeName; static GenericCache() { _typeName = typeof(T).Name; Console.WriteLine($"{typeof(T).Name}"); } public static string GetKey() { return _typeName; } } class Program { static void Main(string[] args) { // 泛型 延迟声明 // 泛型的原理 // object 继承(装、拆箱) for (int i = 0; i < 5; i++) { GenericCache<int>.GetKey(); GenericCache<string>.GetKey(); GenericCache<long>.GetKey(); GenericCache<decimal>.GetKey(); GenericCache<double>.GetKey(); }

  

 

   泛型不能在  webservice\wcf 中使用,发布的服务中的类型都必须是确定的

常见的泛型约束:

    public class Generic<T,S> where T:Program,AA,new()  // 类约束、接口约束、无参构造函数约束
                              where S:T   // 类型约束
    {


    }
    public class Generic1<T, S> where T :struct//值类型约束
    {


    }
    public class Generic2<T, S> where T : class  // 引用类型约束
    {


    }

  

posted @ 2020-05-04 14:58  谁说程序猿很猥琐  阅读(166)  评论(0编辑  收藏  举报