我正在尝试创建某种类型的列表.
我想使用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)
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)
| 归档时间: |
|
| 查看次数: |
33415 次 |
| 最近记录: |