泛型详解

1.什么是泛型?

泛型是.net framework 2.0 升级CLR出现的。泛型就是在有相同行为,不同参数类型的时候用到。

2.泛型的基本语法和使用

/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
public class GenericClass<T>
{
}
/// <summary>
/// 泛型方法
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
/// <param name="t">类型参数</param>
/// <returns></returns>
public T Get<T>(T t)
{
    return default(T);
}
/// <summary>
/// 泛型委托
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
/// <param name="t">类型参数</param>
/// <returns></returns>
public delegate T GetDelegate<T>(T t);
/// <summary>
/// 泛型接口
/// </summary>
/// <typeparam name="T">占位符</typeparam>
public interface GenericInterface<T>
{
}

3.泛型约束

  3.1.基类约束(where T:BaseClass)

/// <summary>
/// 父类
/// </summary>
public class Father
{
     public int Id { get; set; }
     public string Name { get; set; }
}
/// <summary>
/// 子类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public void Show<T>(T t) where T: Father
{
      Console.WriteLine($"{t.Name},{t.Id}");
}

  3.2.接口约束(where T:IInterface)

/// <summary>
/// 泛型接口
/// </summary>
/// <typeparam name="T">占位符</typeparam>
public interface GenericInterface<T>
{
}

/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
public class GenericClass<T> where T: GenericInterface<T>
{
}

  3.3.引用类型约束(where T:class)

/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
public class GenericClass<T> where T:class
{
}

  3.4.值类型约束(where T:struct)

/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
public class GenericClass<T> where T:struct
{
}

  3.5.无参数构造函约束(where T:new())          注意:如果有多个约束,无参数构造函约束必须放在约束的最后面

/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T">T 是占位符</typeparam>
public class GenericClass<T> where T:new()
{
}

 

posted @ 2020-08-26 00:04  字里行间  阅读(131)  评论(0编辑  收藏  举报