什么是泛型
-
-
泛型方法:一个方法满足了不同类型的需求:
-
泛型类:一个类满足了不同类的需求
-
泛型接口:一个接口满足了不同接口的需求
-
泛型委托:一个委托满足了不同委托的需求
1 public static void ShowObject (string s){ 2 Console.WriteLine("this is {typeof(s).Name}"); 3 } 4 public static void ShowObject (int i){ 5 Console.WriteLine("this is {typeof(i).Name}"); 6 } 7 ///Object类型的方法 8 ///为什么可以传入Int String Datetime 9 ///1.Object是所有类型的基类 10 ///2.(任何父类出现的地方都可以使用子类来代替)里氏替换原则 11 public static void ShowObject (Object o){ 12 Console.WriteLine("this is {typeof(o).Name}"); 13 } 14 ///泛型的方法 15 public static void show<T>(T t){ 16 Console.WriteLine("this is {typeof(t).Name)"); 17 }
在调用的时候确定参数类型
延迟声明:在开发中,延迟一起可以延迟的处理,能晚点做,就尽量晚点做
泛型在编译之后,泛型参数会生成占位符`
最终会根据调用生成不同的普通方法:
泛型在.NetFramework2已经出来了;
泛型不是语法糖
使用的时候需要确定类型
泛型约束
[泛型支持的几种约束类型]
泛型类的五大约束 1. where T:struct 限定当前参数类型必须是值类型 2. where T:class 限定当前类型参数类型必须是引用类型 3. where T:new() 限定当前参数类型必须有一个无参构造器 4. where T:<base class name> 限定当前参数类型 必须是当前类 或者当前类为基类的类父类名 5. where T:<interface name>限定当前参数类型必须实现指定接口
说明 where T:struct 对于结构约束,类型T必须是值类型 where T:class 类约束指定类型T必须是引用类型 where T:IFoo 指定类型T必须实现接口IFoo where T:Foo 指定类型T必须派生自基类Foo where T:new() 这是一个构造函数约束,指定类型T必须有一个默认构造函数 where T1:T2 这个约束也可以指定,类型T1派生自泛型类型T2
1 /// <summary> 2 /// 增加 了约束,相当于获取了便利;同时也需要付出成本 3 /// 约束 4 /// 基类约束: 约束这个T 就是People ,就约束只能传递People或者Peoplede的子类 5 /// 接口约束: 6 /// 可以调用接口中的方法--权利 7 /// 调用的时候只能传递实现过这个接口的类进入 --义务 8 /// </summary> 9 /// <typeparam name="T"></typeparam> 10 /// <param name="TParamter"></param> 11 public static void Show<T>(T TParamter) where T : People 12 { 13 Console.WriteLine($"{TParamter.ID}"); 14 Console.WriteLine($"{TParamter.Name}"); 15 } 16 public class People 17 { 18 public int ID { get; set; } 19 public string Name { get; set; } 20 }
缓存就是一个暂存区; 字典缓存:静态属性常驻内存
1 /// <summary> 2 /// 字典缓存:静态属性常驻内存 3 /// </summary> 4 public class DictionaryCache 5 { 6 private static Dictionary<Type, string> _TypeTimeDictionart = null; 7 /// <summary> 8 /// 初始化 9 /// </summary> 10 static DictionaryCache() 11 { 12 Console.WriteLine("this is DictionartCache 静态构造函数"); 13 _TypeTimeDictionart = new Dictionary<Type, string>(); 14 } 15 public static string GetCache<T>() 16 { 17 Type type = typeof(T); 18 if (!_TypeTimeDictionart.ContainsKey(type)) 19 {// 没有添加一次 20 _TypeTimeDictionart[type] = $"{typeof(T).FullName}_{DateTime.Now.ToString("yyyyMMddHHmmss.fff")}"; 21 } 22 return _TypeTimeDictionart[type]; 23 } 24 } 25 static void Main(){ 26 27 string s =DictionaryCache.GetCache<string>(); 28 }
泛型缓存: 泛型类会很久调用的不用类型生成不同的副本
1 /// <summary> 2 /// 泛型缓存本质是一个泛型类 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 public class GenericCache<T> { 6 static GenericCache() { 7 Console.WriteLine("this is GenericCache 静态构造函数"); 8 _TypeTime = $"{typeof(T).FullName}_{DateTime.Now.ToString("yyyyMMddHHmmss.fff")}"; 9 } 10 private static string _TypeTime = ""; 11 public static string GetCache() { 12 return _TypeTime; 13 } 14 }
Out 只能做返回值 ,不能做参数,其实是一种为了避开风险而存在的一种约束
逆变