[英]How do I write a generic method that takes different types as parameters?
I have the following extension method to add the elements in one collection to another collection: 我有以下扩展方法将一个集合中的元素添加到另一个集合:
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> list)
{
foreach (var item in list)
{
collection.Add(item);
}
}
This works fine if the IEnumerable list is the same type as the ICollection I'm trying to add it to. 如果IEnumerable列表与我试图将其添加到的ICollection的类型相同,则此方法可以正常工作。 However, if I have something like this:
但是,如果我有这样的事情:
var animals = new List<Animal>();
var dogs = new List<Dog>(); // dog is a subclass of animal
animals.AddRange(dogs); // this line has a compiler error, it can't infer the type
How do I modify my extension method to be able to do something like this, if the type of the IEnumerable is a subclass (or implements the interface) of the T type? 如果IEnumerable的类型是T类型的子类(或实现接口),如何修改我的扩展方法以便能够执行此类操作?
This method will give you what you want: 这个方法会给你你想要的:
public static void AddRange<A,B>(
this ICollection<A> collection,
IEnumerable<B> list)
where B: A
{
foreach (var item in list)
{
collection.Add(item);
}
}
A couple of notes: 几个笔记:
You can do this: 你可以这样做:
public static void AddRange<T,T2>(this ICollection<T> collection, IEnumerable<T2> list) where T2: T {
foreach (var item in list) {
collection.Add(item);
} }
public static void AddRange<TA, TB>(this ICollection<TA> collection,
IEnumerable<TB> list) where TB : TA
(incorporated Craig Walker's comment) (并入Craig Walker的评论)
I would use constraint to restrict the type. 我会使用约束来限制类型。
public static void AddRange<T, TK>(this ICollection<T> collection, IEnumerable<TK> list) where TK : T
{
foreach (var item in list)
{
collection.Add(item);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.