小编evi*_*kos的帖子

如何在运行时优雅地将IEnumerable <T>转换为HashSet <T>而不事先知道T.

简而言之,我需要在编译时不知道转换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>).

c# reflection

0
推荐指数
2
解决办法
2030
查看次数

标签 统计

c# ×1

reflection ×1