创建变量类型列表

Jan*_*Jan 30 c# list

我正在尝试创建某种类型的列表.

我想使用List符号,但我所知道的只是一个"System.Type"

类型a是可变的.如何创建变量类型列表?

我想要类似于这段代码的东西.

public IList createListOfMyType(Type myType)
{
     return new List<myType>();
}
Run Code Online (Sandbox Code Playgroud)

sme*_*cer 48

这样的事情应该有效.

public IList createList(Type myType)
{
    Type genericListType = typeof(List<>).MakeGenericType(myType);
    return (IList)Activator.CreateInstance(genericListType);
}
Run Code Online (Sandbox Code Playgroud)

  • 我意识到这已经过时了,但是@Jan,它解决了你的问题它应该被标记为答案.@kayleeFrye_onDeck你也可以做`typeof(string [])` (3认同)

And*_*zub 19

您可以使用Reflections,这是一个示例:

    Type mytype = typeof (int);

    Type listGenericType = typeof (List<>);

    Type list = listGenericType.MakeGenericType(mytype);

    ConstructorInfo ci = list.GetConstructor(new Type[] {});

    List<int> listInt = (List<int>)ci.Invoke(new object[] {});
Run Code Online (Sandbox Code Playgroud)

  • 问题是我们不知道myType是typeof(int),所以你的最后一个语句不能是List <int>,我们想要像Liar <myType>这样的东西,但当然不能这样做.要创建实例,我们应该使用System.Activator.CreateInstance(myType).但话说回来,如果是myType类型的对象则返回值.并且您必须使用System.Type来查找方法/属性/接口等. (4认同)