泛型 -Generic 【why,原理,与普通方法,object的性能对比如何?泛型类、泛型方法、泛型接口、泛型委托,泛型约束,协变 逆变,泛型缓存】
一.why:我们为什么要用泛型?
首先来看一下这个例子:我们打印不同类型的值的写法
/// <summary> /// 打印一个int值 /// </summary> public static void ShowInt(int iValue) { Console.WriteLine("This is ShowInt,parameter={0},type={1}", iValue, iValue.GetType().Name); } /// <summary> /// 打印一个string类型的值 /// </summary> public static void ShowString(string sValue) { Console.WriteLine("This is ShowString,parameter={0},type={1}", sValue, sValue.GetType().Name); } /// <summary> /// 打印people类 /// </summary> public static void ShowPeople(People people) { Console.WriteLine("This is ShowPeople,parameter={0},type={1}", people, people.GetType().Name); }
/*普通方法,object,泛型调用参数里面的方法都来源于次定义*/
int iValue = 20201026; string sValue = "泛型Generic"; People people = new People() { Age = 11,Name="测试" }; /*普通方法*/ Console.WriteLine("--------------------普通方法:-----------------------"); Common.ShowInt(iValue); Common.ShowString(sValue); Common.ShowPeople(people);
结果:
思考1:难道每次需要一个类型,就来定义一个方法,那我们需要很多个不同的类型呢,以上方法有什么区别呢? 怎么才可以只写一个方法同时调用不同的类型呢?
1.参数不一样,参数类型不一样,所以没办法去调用同一个,
思考2:那怎么写一个方法不同的类型都可以调用?在1.0版的时候,还没有泛型这个概念,那么怎么办呢?
为什么可以同时传int,string类型,我们说过:object类型是一切类型的父类,同时面向对象的特性中:
继承:c#三大特性中的继承,子类拥有父类的一切属性和方法;
里氏替换原则:任何父类出现的地方都可以用子类去替换,我们是不是就可以优化为以下写法;
/// <summary> /// c#三大特性中的继承,子类拥有父类的一切属性和方法,里氏替换原则:任何父类出现的地方都可以用子类去替换 /// object类型是一切类型的父类 /// </summary> public static void ShowObject(Object oValue) { Console.WriteLine("This is ShowObject,parameter={0},type={1}", oValue, oValue.GetType().Name); }
/*普通方法,object,泛型调用参数里面的方法都来源于次定义*/
int iValue = 20201026; string sValue = "泛型Generic"; People people = new People() { Age = 11,Name="测试" };
Console.WriteLine("--------------------object-----------------------"); Common.ShowObject(iValue); Common.ShowObject(sValue); Common.ShowObject(people);
结果是不是也是一样:使用Object类型达到了我们的要求,很好的解决了代码的可复用

那么我前面说过【https://www.cnblogs.com/wangwangwangMax/p/5425361.html】,数组,对象,string是引用类型,它们的值是存在堆里面的,而所有的值类型都是存储于栈里面,使用object类型,就会存在装箱拆箱,性能损耗方面的问题,
而微软在C#2.0的时候推出了泛型,就可以很好的解决上面的问题,那下面我们就写一个泛型方法来比较一下。
1 写法结构:方法后面有一个<>尖括号,eg:ShowList<T>(T Value),类型参数T实际上就是一个类型声明,表示是一个占位符,也可以使用任何非保留字,eg:S 或者 W
/// <summary> /// 声明一个泛型方法 /// 结构:方法后面有一个<>尖括号ShowList<T>(T Value) /// </summary> /// <typeparam name="T">typeparam:类型参数,T实际上就是一个类型声明,表示是一个占位符,也可以使用任何非保留字</typeparam> /// <param name="Value">param:参数</param> /// 正因为没有写死,才拥有了无限的可能 public static void ShowList<T>(T Value) { Console.WriteLine("This is ShowList,parameter={0},type={1}", Value, Value.GetType().Name); }
/*普通方法,object,泛型调用参数里面的方法都来源于次定义*/
int iValue = 20201026; string sValue = "泛型Generic"; People people = new People() { Age = 11,Name="测试" };
Console.WriteLine("--------------------泛型的声明和使用-----------------------"); Generic.ShowList<int>(iValue); Generic.ShowList<string>(sValue); Generic.ShowList<People>(people);
以上调用,我们还可以写成如下格式:
Generic.ShowList(iValue);
Generic.ShowList(sValue);
Generic.ShowList(people);
如果可以从参数类型推断,那么就可以省略类型参数,这种由编译器提供的功能就叫做语法糖
结果:

这个地方,我们在调用泛型方法的时候,才指定了具体的类型;
总结: 【泛型说白就是一个东西,完成以前多个东西能完成的东西】
二.那泛型究竟是如何How工作的呢?
![]()
泛型原理:声明的不知道是什么类型,编译的时候用【占位符-`1、`2】来表示
调用的时候再来指定具体的参数类型
思想:【延迟声明:推迟一切可以推迟的东西,能晚点做的事,就晚点做】
三.那他们三者之间的性能又如何呢?
我们写一个测试例子看一下,
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LearnGenericFirst1 { /// <summary> /// 性能测试 /// </summary> public class Monitor { public static void Show() { Console.WriteLine("--------------------Monitor-----------------------"); int iValue = 20201031; string sValue = "20201031"; long commonSecond = 0; long objectSecond = 0; long genecirSecond = 0; { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000_000; i++) { ShowInt(iValue); } watch.Stop(); commonSecond = watch.ElapsedMilliseconds; Console.WriteLine("循环1亿次,普通方法需要{0}ms", commonSecond); } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000_000; i++) { //intList.Add(i);//public virtual int Add(object value);存在装箱拆箱操作 ShowObject(iValue);//存在装箱拆箱操作 } watch.Stop(); objectSecond = watch.ElapsedMilliseconds; Console.WriteLine("循环1亿次,object需要{0}ms", objectSecond); ShowObject(sValue); // ShowObject(sValue);("arrylist还能再添加一个string类型的数据进去,指定int,中途插入一个别的类型进去,处理数据的时候就会出问题,而泛型则不能," + // "相比较更好的确保了声明类型的调用,安全"); } { Stopwatch watch = new Stopwatch(); watch.Start(); List<int> intList = new List<int>();//iValue for (int i = 0; i < 100_000_000; i++) { //intList.Add(i);//public void Add(T item);泛型类下面的泛型方法 Show(iValue); } watch.Stop(); genecirSecond = watch.ElapsedMilliseconds; Console.WriteLine("循环1亿次,泛型需要{0}ms", genecirSecond); } } #region privateMethod private static void ShowInt(int iParameter) { } private static void ShowObject(object iParameter) { } private static void Show<T>(T tParameter) { } #endregion } }
Console.WriteLine("--------------------普通方法,object与泛型的性能测试-----------------------"); Monitor.Show();
结果:

结论:泛型方法的性能跟普通方法一致,是最好的,而且还能一个方法同时满足多个不同类型,相比object,泛型更安全
四.泛型类 class+类名+<尖括号>
以上我们说了泛型方法,下面说一下泛型类,结构,class+类名+<尖括号>
///一个类,满足不同类型的需求 public class GenericClass<S, T> { /// <summary> /// Show<S, T,W>如果类里面声明了类型,方法里面就不用再次声明,下面列举两种写法的延伸 /// </summary> /// <typeparam name="W">Show<W>S s,T t,W w也可以小写,s,t都来自泛型类,w则来自于泛型方法</typeparam> public static void Show<W>(S s,T t,W w) { } public static void Show(S s, T t) { } public static void Show() { } }
五.泛型接口,interface+接口名+<尖括号>
/// <summary> /// 泛型接口:没有public static /// 一个接口满足不同类型的需求; /// </summary> /// <typeparam name="X"></typeparam> /// <typeparam name="Y"></typeparam> public interface IGenericInterface<X,Y> { void Show<W>(X x, Y y, W w); void Show(X x, Y y); void Show(); //泛型类型的返回值 X GetT(X x); }
六.泛型委托也是差不多的结构 delegate +返回值+命名+<尖括号>
/// <summary> /// 泛型委托:一个委托满足不同类型的需求 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="W"></typeparam> public delegate void DoSomethingHandler<T, W>();
七.泛型类,接口继承的问题
public class GenericClassChild2 : GenericClass<S, T> { }
思考:参考上面一个列子,在代码里面,还没编译,继承了一个泛型的父类,这种方式为什么会报错呢?
子类GenericClassChild2本身没有一个泛型的概念【非泛型,封闭/普通类:所有类型都是确定的】,它不知道父类【非封闭类型/开放性类型:泛型类型没指定】的<S, T>是什么类型,在调用的时候必须确定类型,
如果父类是个非封闭性类型,那么它无法作为封闭类型的父类,可以把父类指定成具体类型,如下写法【泛型类型指定,变成了封闭类型】就可以继承父类了
/// <summary> /// 泛型类的继承实例1 /// </summary>
public class GenericClassChild2 : GenericClass<int,string> { }
/// <summary> /// 泛型类的继承实例2 /// </summary> public class GenericClassChild1<S, T> : GenericClass<S, T> { }
/// <summary> /// 泛型类的继承实例3--父类是个封闭类型【已经指定好了类型就不是泛型类】也就是一个普通类型,而子类是一个泛型,这个可以有 /// </summary> public class GenericClassChild2<T> : GenericClass<int, string> { }
/// <summary> /// 泛型接口的继承原理和泛型类继承一样 /// </summary> public interface IGenericInterfaceChild1<X,Y>: IGenericInterface<X,Y> { } public interface IGenecirInterfaceChild2 : IGenericInterface<int, string> { } public interface IGenecirInterfaceChild2<S,T> : IGenericInterface<int, string> { }
八.泛型约束
泛型一个东西可以当做多个东西来使用,满足不同的参数类型,正是没有约束,任意类型都可以传进来,我们也不知道它是什么,所以我们就会有一些约束的概念,泛型约束一共有⑤种

为什么要使用约束呢?让我们先来看一段下面的例子:
1 /// <summary> 2 /// People实体 3 /// </summary> 4 public class People 5 { 6 public int Id { get; set; } 7 public int Age { get; set; } 8 public string Name { get; set; } 9 public void SayHi() 10 { 11 Console.WriteLine("Hi, {0} Good,Morning!",this.Name); 12 } 13 } 14 15 /// <summary> 16 /// 中国人实体 17 /// </summary> 18 public class Chinese : People,iSports 19 { 20 public string KangFu { get; set; } 21 public string Characteristic { get; set; } 22 public void Pingpang() 23 { 24 Console.WriteLine("Pingpang"); 25 } 26 public void Majiang() 27 { 28 Console.WriteLine("Majiang"); 29 } 30 } 31 32 public class Japanese : iSports 33 { 34 public int Id { get; set; } 35 public string Name { get; set; } 36 37 public void Pingpang() 38 { 39 Console.WriteLine("打乒乓球"); 40 } 41 } 42 43 /// <summary> 44 /// 接口 45 /// </summary> 46 public interface iSports 47 { 48 void Pingpong(); 49 }
/// <summary> /// ShowObject方法 /// </summary> /// <param name="oValue"></param> public static void ShowObject(Object oValue) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(GenecirConstraint), oValue, oValue.GetType().Name); People people = (People)oValue; Console.WriteLine("This is {0},people.Id={1},people.name={2}", typeof(GenecirConstraint), people.Id, people.Name); people.SayHi(); }
Chinese chinese = new Chinese() { Id = 5, Name = "湖南" }; Japanese japanese = new Japanese() { Id = 6, Name = "福原爱" }; GenecirConstraint.ShowObject(chinese); GenecirConstraint.ShowObject(japanese);

思考1:上面这面代码为什么会报错呢?
Object 方法因为可以出入任何类型,没有限制,如果传入的类型不匹配,就会发生异常(类型安全问题),就像交通行驶,有了交规,有了红绿灯,才更安全

2.思考2:why为什么普通方法可以直接调用people类里面的属性和方法,为什么泛型做不到?--因为被限制了,那我怎么让泛型可以调用people类里面的属性和方法呢?这时候我们就用到了泛型约束
1.泛型类约束:【:where T 类名】
/// <summary> /// 泛型约束:没有约束就没有自由 /// 不管是泛型类,泛型接口,泛型委托后面都可以使用泛型约束 /// 结构:Show<S>(S 后面+Where 声明类型S :【<S>(S Value) where S :】表明这个泛型"S"必须满足这个People的约束 /// where T:BaseModel 【where:保留关键字,用来做泛型约束的; :表示被谁约束】 /// </summary>
/// <summary> /// 这是基类约束,它有两个特点 /// 第一个特点:可以把T当成一个基类,我们可以直接使用它里面的属性和方法--有了约束,就有了权力;
///如果只是单纯的传一个People,那么性能上跟上面例子中的普通方法没什么区别,但是使用泛型会更加灵活 /// </summary> public static void Show<S>(S sValue) where S:People { Console.WriteLine("This is Show,parameter={0},type={1}", sValue, sValue.GetType()); Console.WriteLine("This is Show,people.Id={0},people.name={1}", sValue.Id,sValue.Name); sValue.SayHi(); }
思考:为什么调用这个方法传入一个iValue,sValue它会报错,而people不会?

Console.WriteLine("--------------------泛型基类约束的调用-----------------------"); GenecirConstraint.Show(people); GenecirConstraint.Show<Chinese>(new Chinese() { Id = 1, Name = "重庆", Characteristic = "重庆火锅" }); //可以直接把类型参数去掉不写,编译器会自动推算 GenecirConstraint.Show(new Chinese() { Id = 2, Name = "上海", Characteristic = "上海混沌" });
Console.WriteLine("结论:泛型基类约束的第二大特性,在调用的时候,只能传入它或者它的子类【只能是继承了它的子类】");
结果:

2.泛型接口约束:【:where T 接口名】
/// <summary> /// 接口约束,只能使用接口里面的方法 /// </summary> /// <typeparam name="S"></typeparam> /// <param name="sValue"></param> public static void Sports<S>(S sValue) where S : iSports { Console.WriteLine("This is Show,parameter={0},parameter={1}", sValue, sValue.GetType().Name); sValue.Pingpang(); }
Console.WriteLine("--------------------泛型接口约束调用:-----------------------"); GenecirConstraint.Sports(new Chinese() { Id = 3, Name = "北京", Characteristic = "北京烤鸭" });
//实体类里japanese继承了iSports所以可以了调用此方法 GenecirConstraint.Sports(japanese); //实体类里people类没有继承了iSports接口所以不可以了调用此方法 //GenecirConstraint.Sports(people);
结果:

public interface iDaily { void Majiang(); }
/// <summary> /// 同时被一个类和接口约束,:基类在前面,接口在后面 /// 只能被一个父类约束,但可以被多个接口约束 /// </summary> /// <typeparam name="S"></typeparam> /// <param name="sValue"></param> public static void ClassInterFaseMeanwhile<S>(S sValue) where S : People, iSports, iDaily { Console.WriteLine("This is Show,parameter={0},parameter={1}", sValue, sValue.GetType().Name); Console.WriteLine("This is Show,people.Id={0},people.name={1}", sValue.Id, sValue.Name); sValue.SayHi(); sValue.Pingpang(); sValue.Majiang(); }
Console.WriteLine("--------------------泛型基类和接口约束同时调用:-----------------------"); GenecirConstraint.ClassInterFaseMeanwhile(chinese);
结果:

3.除了泛型类约束,接口约束,还有三种的基本的约束,这三种约束比较特殊,分别是:引用类型约束,值类型约束,无参数构造函数约束
/// <summary> ///引用类型约束:【 where T : class ,T一定是一个引用类型】 ///where T : String //密封内约束的不行,因为没有意义 /// </summary> /// <returns></returns> public static T GetT<T>() where T : class //T tParameter { return null;//引用类型都可以返回null,如果没有where T : class这个约束就会报错,它还有可能会是值类型 } /// <summary> /// 值类型约束:【where T : struct】 /// </summary> public static T GetValuetype<T>(T tParameter) where T : struct { //return 0;//这边返回0为什么会报错呢?值类型不仅是int,还有其它类型,eg:长整型,小数 return default(T);//default是一个关键字,它会根据T的类型去获取一个默认值 } /// <summary> /// 无参数构造函数约束【where T : new()】 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetParameterlessConstructor<T>() where T : new() { return new T();// }
/// <summary> /// 几个约束可以叠加,用逗哈隔开即可 /// 如果有多个参数的情况,约束可以直接写,不需要用逗号 /// </summary> /// <typeparam name="T"></typeparam> public static T Getconstraint<T,S>() where T : Chinese, iSports, iDaily, new()//,class无意义 where S:class { return new T();// }
九. 协变 逆变
1.什么是协变逆变?产生的背景?它的前提是什么,它能做些什么?

1. 协变逆变:泛型委托,泛型接口,前面又加上了 in , out ,所以称为了泛型的协变,逆变,让我们继续往下面看例子
//定义了一个动物的实体类 public class Animal { public int Id { get; set; } } //定义了一个猫猫的实体类,继承Animal类 public class Cat:Animal { public string Name { get; set; } }
2.产生的背景:
我们在平时写代码的时候,是不是就会遇到这样的情况,这是普通方法的写法
{ Animal animal1 = new Animal(); Animal animal2 = new Cat();//父类变量用子类实例化,猫咪当然是动物 Cat cat1 = new Cat(); //Cat cat2 = new Animal();//子类变量不能用父类实例化 //父类出现的地方可以用子类代替,子类出现的地方则不能用父类代替,猫咪属于动物,动物不一定只有猫咪 }
但是,我们在用泛型写的时候,却怎么都不对?Why?

//当然我们可以用这种方式实现 List<Animal> animals3 = new List<Cat>().Select(c => (Animal)c).ToList();
1 /*按照上面普通方法的逻辑,猫属于动物,可是这种写法为什么不可以呢?Why不成立呢?*/ 2 //List<Animal>是个类,List<Cat>也是个类,前面说过泛型编译的时候只是个占位符,调用的时候就确定了,前面就确定了是List<Animal>, 3 //而后面又是List<Cat>,二者没有父子关系,List没关系 4 //换句话说就是:你是个list实例,我也是个list 实例,我们又不是继承关系,所以不能 5 //语法不通过,语义上可以,这就是协变逆变产生的背景 7 //我们使用泛型的原因也正是书写方便
3.协变 IEnumerable<out T> out <out T>协变covariant 修饰返回值 效果:让右边可以用子类 条件:T只能返回结果,就不能再作为参数
/*--------------------------------------------------协变Out----------------------------------------------------*/ /// <summary> /// out 协变 T 就只能做返回值 ,不能做参数 /// </summary> /// <typeparam name="T"></typeparam> public interface ICustomerListOut<out T> { //void Show(); //void Show(T t);//协变 T 就只能做返回值 ,不能做参数 T Get();//泛型类型的返回值 } /// <summary> /// 这种情况是可以的,泛型类继承该接口 /// </summary> /// <typeparam name="T"></typeparam> public class CustomerListOut<T> : ICustomerListOut<T> { public T Get() { return default(T); } }
/*--------------------------------------------------协变out----------------------------------------------------*/ { //public interface IEnumerable<out T> : IEnumerable //协变:IEnumerable<out T>【效果:让右边可以用子类】条件:T只能返回结果,就不能再作为参数 //协变作用是防止有了泛型包装之后,导致[父子]继承关系失效,进一步的加强了泛型的方便些 IEnumerable<Animal> animals1 = new List<Animal>(); IEnumerable<Animal> animals2 = new List<Cat>(); //我们定义了一个支持协变的接口,那我们也是不是也可以用这个接口定义一个支持协变的cat类 //局限性:out修饰协变后,T只能作为返回值,而不能作为参数 //左边是定义的一个支持协变的接口,右边则是继承协变接口的泛型类 ICustomerListOut<Animal> customerList1 = new CustomerListOut<Animal>(); ICustomerListOut<Animal> customerList2 = new CustomerListOut<Cat>(); }
4.逆变 in <in T>逆变contravariant 修饰传入参数 逆变:让右边可以用父类,In修饰逆变后,T只能当参数,不能作返回值
1 /*--------------------------------------------------逆变In----------------------------------------------------*/ 2 public interface ICustomerListIn<in T> 3 { 4 //T Get();//逆变T就不能作为返回值,只能作为参数 5 void Show(T t); 6 } 7 /// <summary> 8 /// 泛型类继承了一个支持逆变的泛型接口 9 /// </summary> 10 public class CustomerListIn<T>:ICustomerListIn<T> 11 { 12 public void Show(T t) 13 { 14 Console.WriteLine(t); 15 } 16 }
1 /*--------------------------------------------------逆变In----------------------------------------------------*/ 2 { 3 //逆变:让右边可以用父类,In修饰逆变后,T只能当参数,不能作返回值 4 ICustomerListIn<Cat> listIn1 = new CustomerListIn<Cat>(); 5 ICustomerListIn<Cat> listIn2 = new CustomerListIn<Animal>(); 6 listIn1.Show(new Cat()); 7 }
5.协变,逆变一起
1 /*--------------------------------------------------协变Out逆变In一起----------------------------------------------------*/ 2 public interface ITogetherList<in inT,out outT> 3 { 4 void Show(inT t); 5 outT Get(); 6 outT Do(inT t); 7 } 8 public class TogertherList<Y1, Y2> : ITogetherList<Y1, Y2> 9 { 10 public void Show(Y1 y) 11 { 12 Console.WriteLine("This is {0}", y.GetType().Name); 13 } 14 public Y2 Get() 15 { 16 Console.WriteLine(typeof(Y2).Name); 17 return default(Y2); 18 } 19 public Y2 Do(Y1 y) 20 { 21 Console.WriteLine("This is {0}", y.GetType().Name); 22 Console.WriteLine(typeof(Y2).Name); 23 return default(Y2); 24 } 25 }
/*--------------------------------------------------协变Out逆变In一起的例子----------------------------------------------------*/ { ITogetherList<Cat,Animal > list1= new TogertherList<Cat,Animal>(); ITogetherList<Cat, Animal> list2 = new TogertherList<Cat, Cat>();//协变:左边是父类的时候,协变可以替换为子类 ITogetherList<Cat, Animal> list3 = new TogertherList<Animal, Animal>();//逆变:左边是子类的时候,协变可以替换为父类 ITogetherList<Cat, Animal> list4 = new TogertherList<Animal, Cat>();//协变+逆变 }
总结: 
1 /// 所谓协变逆变都是只针对泛型的 2 /// 只能放在接口或者委托的泛型参数前面 3 /// public delegate TResult Func<in T, out TResult>(T arg);
十. 泛型缓存【说白了就是把数据存一下,下次直接用,常用做法,就是搞一个内部静态字典,因为字典不容易丢失,并且可以放很多项】
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.Threading.Tasks; 7 8 namespace LearnGenericFirst1 9 { 10 /// <summary> 11 /// 泛型缓存 12 /// 缓存是属于大型网站架构必备的一部分,提升性能的第一步 13 /// 缓存:说白了就是把数据存一下,下次直接用,常用做法,就是搞一个内部静态字典,因为字典不容易丢失,并且可以放很多项 14 /// </summary> 15 public class GenericCacheTest 16 { 17 public static void show() 18 { 19 for (int i = 0; i < 5; i++) 20 { 21 Console.WriteLine(GenericCache<int>.GetCache()); 22 Thread.Sleep(10); 23 Console.WriteLine(GenericCache<long>.GetCache()); 24 Thread.Sleep(10); 25 Console.WriteLine(GenericCache<DateTime>.GetCache()); 26 Thread.Sleep(10); 27 Console.WriteLine(GenericCache<string>.GetCache()); 28 Thread.Sleep(10); 29 Console.WriteLine(GenericCache<GenericCacheTest>.GetCache()); 30 Thread.Sleep(10); 31 } 32 } 33 34 /// <summary> 35 /// 以前的缓存【 字典缓存】,静态属性常驻内存 36 /// </summary> 37 /// <typeparam name="T"></typeparam> 38 /// <returns></returns> 39 public class DictionaryCache 40 { 41 private static Dictionary<Type, string> _TypeTimeDictionary = null; 42 /// <summary> 43 /// 由我们的CLR保障第一次启用的时候会执行的,而且只执行一次 44 /// </summary> 45 static DictionaryCache() 46 { 47 Console.WriteLine("This is DictionaryCache 静态构造函数!"); 48 _TypeTimeDictionary = new Dictionary<Type, string>(); 49 } 50 public static string GetCache<T>() 51 { 52 Type type = typeof(Type); 53 //首先判断一下字典里面有没有,有直接从字典里拿,没有就计算一下,把数据放进去 54 if (!_TypeTimeDictionary.ContainsKey(type)) 55 { 56 _TypeTimeDictionary[type] = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff")); 57 } 58 return _TypeTimeDictionary[type]; 59 } 60 61 } 62 63 /// <summary> 64 /// GenericCache<T>每个不同的T,CLR都会生成一份不同的副本 65 /// 适合不同类型,需要缓存一份数据的场景,效率高 66 /// 静态的东西是放在内存中,且唯一,不会被回收的,但是;如果静态的东西被放在泛型里面,一切都变化了,会随着指定的不同类型,编译器会为它生产不同的副本 67 /// 局限性:泛型缓存一个类型,只能存一个值,两个值则存不了 68 /// </summary> 69 /// <typeparam name="T"></typeparam> 70 public class GenericCache<T> 71 { 72 static GenericCache() 73 { 74 Console.WriteLine("This is DictionaryCache 静态构造函数!"); 75 _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff")); 76 } 77 private static string _TypeTime = ""; 78 public static string GetCache() 79 { 80 return _TypeTime; 81 } 82 } 83 84 } 85 }
本文来自博客园,作者:wangwangwangMax,转载请注明原文链接:https://www.cnblogs.com/wangwangwangMax/p/13906297.html

浙公网安备 33010602011771号