1.泛型(Generic)

1、泛型缓存

泛型就是封装,将重复的工做简单化函数

1.泛型方法spa

public static void Show<T>(T tParameter)
{
  Console.WriteLine("This is {0}, parameter = {1}, type = {2}", typeof(CommonMethod).Name, tParameter.GetType(), tParameter);
}

2.泛型类code

public class GenericClass<T>{}

3.泛型接口orm

public interface GenericInterface<I>{}

4.泛型委托
blog

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.泛型缓存string

    /// <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-参数)
相关文章
相关标签/搜索