【问题标题】:Create List<T> using GetType()使用 GetType() 创建 List<T>
【发布时间】:2010-08-11 00:00:37
【问题描述】:

是否可以使用 GetType() 创建 List 或 IEnumerable。

// If T is Type of Contact I want to Return List<Contact>

Test(typeof(Contact));//return List<Type>

    public static IEnumerable<T> Test<T>(T t)
    {
        return new List<T>();  //return List<Type>

    }

【问题讨论】:

  • 停下来想出一个合理的用例,你的问题就会消失。你想做什么?

标签: c# generics list reflection ienumerable


【解决方案1】:
 public static IList GetList(Type type)
 { 
    return (IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
 }

【讨论】:

  • 哦,相信我,后面的 GetList 有时会非常有用。
  • @Chris:我把它编辑了,很惊讶你还能看到它。 :)
  • 是的,我看到它的时候是第 2 版,当时它还在那里。顺便说一句,任何人都可以通过单击“已编辑的 X”日期戳来查看旧版本的已编辑问题和答案,所以...
  • +1 @Chris:太不可思议了,但我不知道这个功能。
  • 我自己花了很长时间才找到它。或者更准确地说,要意识到它适用于所有问题和答案,而不仅仅是我自己的。
猜你喜欢
  • 1970-01-01
  • 2011-12-31
  • 2012-06-16
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多