c#进阶 之 泛型

泛型基础知识

1.什么是泛型?

  泛型(Generic) 允许您延迟编写类或方法中的编程元素的数据类型的规范,直到实际在程序中使用它的时候

 ......

2.泛型类,泛型方法,泛型接口,泛型委托

(1)List泛型

Object类型是不安全的

 (2)Dictionary

 (3)自定义泛型

 public class MyGenneric<T>
 {
   private T t;
   public MyGenneric(T t)
   {
     this.t = t;
   }

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

//-------------------------自定义泛型-----------------
MyGenneric<string> myGeneric = new MyGenneric<string>("这是自定义泛型");
myGeneric.Show();

(4)泛型方法

 public void ShowList<Tm>(Tm tm)
{
    Console.WriteLine(tm.ToString());
}


myGeneric.ShowList<string>("这是泛型方法");
myGeneric.ShowList<int>(88888);

3.泛型的好处和原理

 好处:最大的优点就是通用性,写一个方法和类以后,在很多地方可以使用

 exe/dll(主要区别:exe有文件入口) --- metadata(元数据:描述exe/dll文件的一个数据清单)----反射(Reflection)用来操作获取元数据

 注:clr/jit也需要读取到metadata,那么就需要用到反射

 泛型在编译时是通过<>来占一个位置,然后 在CLR/JIT(运行时)确定具体类型

5.泛型约束

(1)new()约束 --表示T类型只能接收带一个无参数的构造函数

 class Student  //普通类
    {
        //默认有一个无参数的构造
    }

public static void Main(string[] args)
        {
            Student student = new Student();
            Show(student);
            
        }


        public static void Show<T>(T t) where T : new()
        {
            Console.WriteLine(t);
        }

(2) struct 值类型约束

public static void Show<T>(T,t)
    where T:struct
{

}  

(3)class 引用类型约束

public static void Show<T>(T,t)
    where T:class,new() //可以多种约束
{

}  

(4)自定义类型约束(基类型约束,接口类型约束)

public static void Person<S,K,D>(S s)
  where S:Student, IStudent,IStudent<K> //基类约束只能有一个
  where K:struct
  where D:class,new()
  {

  }

6.协变 逆变  (了解)

People people = new People();
People people1 = new Teacher();//people 父类  Teacher子类 继承父类
Teacher teacher = new Teacher();
List<People> peopleList = new List<People>();
//[1]//从现实生活中,应该是正确的CIA对,但是两者不是同一个类型
//两者不是一个类型,报错,语法规则  .net2.0和3.0才有协变逆变
//List<People> peopleList1 = new List<Teacher>();
//[2]协变和逆变是针对泛型接口和泛型委托来说的,离开了他们就没有这个说法
//[3]out关键字代表是协变,in代表是逆变
//什么情况下使用:需要解决 泛型类型 子类 实例化父类时,或者父类实例化子类

IListOut<People> listOut = new ListOut<People>();
IListOut<People> listOut1 = new ListOut<Teacher>();//协变 T 只能作为返回类型

IListIn<Teacher> k = new ListOut<Teacher>();
IListIn<Teacher> kk = new ListOut<People>(); //逆变 只能作为参数类型
interface IListOut<out T>
{
    T GetT();
}

interface IListIn<in T>
{
    void Show(T t);
}

class ListOut<T> : IListOut<T>,IListIn<T>
{
    public T GetT()
    {
        return default(T);//default 关键字,若是值,类型默认返回0,若引用类型,则默认返回null
    }

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

总结: 泛型的用处:让泛型类,泛型方法,泛型接口,泛型委托更--通用

7.泛型缓存

原文地址:https://www.cnblogs.com/zmztya/p/14604163.html