1.泛型(Generic)

一、泛型

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

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-参数)

猜你喜欢

转载自www.cnblogs.com/tq1314/p/12196160.html