C# 泛型和泛型约束
2020-11-01 11:31 默默的码农哥 阅读(550) 评论(0) 编辑 收藏 举报C#中的泛型,大致有如下几种:泛型方法,泛型类,泛型接口,泛型委托,泛型约束等
使用泛型的好处一个是为了减少代码量,更主要的是能提高效率,不需要进行拆箱和装箱的操作。
下面是写的简单的例子,共勉,加深理解和熟悉。
/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T"></typeparam>
public class Calculate<T>
{
/// <summary>
/// 泛型委托
/// </summary>
/// <param name="a"></param>
private delegate void RemoveS(T a);
/// 泛型类
/// </summary>
/// <typeparam name="T"></typeparam>
public class Calculate<T>
{
/// <summary>
/// 泛型委托
/// </summary>
/// <param name="a"></param>
private delegate void RemoveS(T a);
RemoveS rs = null;
public Calculate()
{
rs= new RemoveS(Remove);
List = new List<T>();
}
public Calculate()
{
rs= new RemoveS(Remove);
List = new List<T>();
}
public List<T> List { get; set; }
/// <summary>
/// 泛型方法
/// </summary>
/// <param name="a"></param>
public void Add(T a)
{
List.Add(a);
Console.WriteLine("List :" + string.Join("&", List));
}
public void Remove(T a)
{
if (List.Contains(a))
{
List.Remove(a);
}
Console.WriteLine("List :" + string.Join("&", List));
}
}
/// <summary>
/// 泛型方法
/// </summary>
/// <param name="a"></param>
public void Add(T a)
{
List.Add(a);
Console.WriteLine("List :" + string.Join("&", List));
}
public void Remove(T a)
{
if (List.Contains(a))
{
List.Remove(a);
}
Console.WriteLine("List :" + string.Join("&", List));
}
}
调用的例子
static void Main(string[] arg)
{
Calculate<int> cal = new Calculate<int>();
cal.Add(2);
cal.Add(2);
cal.Remove(2);
Console.ReadLine();
{
Calculate<int> cal = new Calculate<int>();
cal.Add(2);
cal.Add(2);
cal.Remove(2);
Console.ReadLine();
Calculate<Animal> cal_animal = new Calculate<Animal>();
Animal a = new Animal { Name = "Dog" };
cal_animal.Add(a);
cal_animal.Remove(a);
Animal a = new Animal { Name = "Dog" };
cal_animal.Add(a);
cal_animal.Remove(a);
}
泛型接口
泛型接口实现
调用实现
2、泛型约束
值类型约束
Where T is Struct,就是在使用的时候只能使用值类型泛型,如INT,Struct,Double等
引用类型约束
Where T is Object,
实例化需要带参构造函数约束
Where T is New(Param param);