我动态创建了一个类(找到它 here )但我不明白为什么我不能用它来创建列表?
var myType = CompileResultType();
var myObject = Activator.CreateInstance(myType);
var myList = new List<myObject>();
// Error: The type or namespace name 'myObject'
// could not be found (are you missing a using directive
// or an assembly reference?)
我应该怎么做?
最佳答案
它们被称为泛型类型参数,因为它们需要类型,而不是实例。因此,您需要知道实际类型或使用反射创建列表对象。
Type listType = typeof(List<>);
Type dynamicClassType = listType.MakeGenericType(myObject.GetType());
object myList = Activator.CreateInstance(dynamicClassType);
但是,您无法以任何有意义的方式使用该实例,因为它是一个对象。
您可以按照 Avner Shahar-Kashtan's answer 中的建议将其转换为
IList
并使用非泛型方法。IList myList = (IList)Activator.CreateInstance(dynamicClassType);
您也可以通过反射调用列表实例的方法。
// roughly MethodInfo addMethod = myList.GetType().GetMethod("Add"); addMethod.Invoke(myList, objectToAdd);
或按照 Cuong Le's answer 中的建议进行操作并使用
dynamic
作为列表实例的类型。dynamic myList = Activator.CreateInstance(dynamicClassType);
关于c# - 为什么我不能使用 myObject 创建 List<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17802562/