简而言之,我需要在编译时不知道转换IEnumerable list(带有值IEnumerable<T>).我认为可以做到的唯一方法如下,但我发现它非常难看.HashSet<T> setT
public IEnumerable GetHashSet(IEnumerable source)
{
Type itemType = source.GetType().GetGenericArguments()[0];
Type listOpen = typeof(List<>);
Type listClosed = listOpen.MakeGenericType(new Type[] { itemType });
IList list = Activator.CreateInstance(listClosed) as IList;
foreach (var obj in source)
list.Add(obj);
Type hashSetOpen = typeof(HashSet<>);
Type hashSetClosed = hashSetOpen.MakeGenericType(new Type[] { itemType });
return Activator.CreateInstance(hashSetClosed, list) as IEnumerable;
}
Run Code Online (Sandbox Code Playgroud)
问题是,HashSet<T>没有任何方法可以通过某些非通用接口添加对象(相比之下,List<T>有IList.Add(object)).它也没有一个带有"裸"IEnumerable的构造函数(也没有List<T>).