1.泛型(Generic)

放肆的年华 提交于 2020-01-15 13:36:29

一、泛型

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

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-参数)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!