【发布时间】:2010-12-08 02:53:04
【问题描述】:
HashSet 没有 AddRange 方法,所以我想为它写一个扩展方法。这就是我所拥有的:
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> list)
{
foreach (var item in list)
{
collection.Add(item);
}
}
我有一个基类 Media 和一个派生类 Photo。这是我想要工作的代码:
var photos = new List<Photo>();
var media = new HashSet<Media>();
media.AddRange(photos);
但是,编译器告诉我,当我尝试使用AddRange() 时,它无法将List<Photo> 转换为IEnumerable<Media>。我很确定这是因为我在扩展方法中有IEnumerable<T>,但是我如何编写它以使类型与AddRange<T>中的类型不同?
【问题讨论】:
标签: c# generics extension-methods hashset