一、泛型

泛型就是封装,将重复的工作简单化

1.泛型方法

public static void show<t>(t tparameter)
{
  console.writeline("this is {0}, parameter = {1}, type = {2}", typeof(commonmethod).name, tparameter.gettype(), tparameter);
}

2.泛型类

public class genericclass<t>{}

3.泛型接口

public interface genericinterface<i>{}

4.泛型委托

public delegate void do<t>();

5.泛型约束

public static void show<t>(t tparameter) where t : people//基类约束
                                       //where t : isport//接口约束
{
  console.writeline("this is {0}, parameter = {1}, type = {2}", typeof(commonmethod).name, tparameter.gettype(), tparameter);
  console.writeline($"{tparameter.id} {tparameter.name}");
}
public t get<t>(t t)
//where t : class//引用类型约束,才可以返回null //where t: struct//值类型约束 where t: new()//无参构造函数约束 {   //return null;   //return default(t);//default是个关键字,会根据t的类型去获取一个值   return new t();//只要有无参数构造函数,都可以传进来   //throw new exception(); }

6.泛型缓存

    /// <summary>
    /// 每个不同的t,都会生成一份不同的副本
    /// 适合不同类型,需要缓存一份数据的场景,效率高
    /// 局限:只能为某一类型缓存
    /// </summary>
    /// <typeparam name="t"></typeparam>
    public class genericcache<t>
    {
        static genericcache()
        {
            console.writeline("this is genericcache 静态构造函数");
            _typetime = string.format("{0}_{1}", typeof(t).fullname, datetime.now.tostring("yyyymmddhhmmss.fff"));
        }

        private static string _typetime = "";

        public static string getcache()
        {
            return _typetime;
        }
    }
7.泛型协变(out-返回值)、逆变(in-参数)