泛型可以用於類,也可以用於函數。如
泛型類:
public class MyClass<T>
{
public T MyElement { get; set; }
}
泛型函數:
public T ReturnElement<T>()
{
throw new NotImplementedException();
}
但是當需要對MyElement進行實例化的時候,卻不能使用new(),只要添加如下代碼即可進行實例化了:
泛型類:
public class MyClass<T> where T: new()
{
public T MyElement { get; set; }
public MyClass()
{
this.MyElement = new T();
}
}
泛型函數:
public T ReturnElement<T>() where T : new()
{
return new T();
}
在這里,where實際上對泛型類型T的一個限定或補充。如果你希望T是一個int的集合,這個集合可以是List<int>,也可以是HashSet<int>等等,只要它們都是從ICollection繼承而來的,則可以添加對類型T的限定,同時要保證它還是可以實例化的:
public T ReturnElement<T>()
where T : ICollection<int>, new()
{
return new T();
}
進一步,如果希望放寬集合中元素的類型,比如只要是int,double等可比較的類型,它們都是從IComparable繼承而來,則可以繼續添加如下限定:
public T ReturnElement<T, S>()
where T : ICollection<S>, new()
where S : IComparable
{
return new T();
}
C# 的泛型類型提供了很方便的機制,非常方便地就能舉一反三。