[英]Instantiate class using Type t as reflected
我有以下代码。 t
在第二行显示为无效。
Cannot resolve symbol 't'
如何使用Type t
实例化泛型类。
Type t = currentProperty.PropertyType;
var x = new MyClass<t>();
谢谢
泛型仅是编译时功能,不是运行时功能。 您需要使用反射创建类。
Type t = currentProperty.PropertyType;
Type desiredType = typeof(MyClass<>).MakeGenericType(t);
var instance = Activator.CreateInstance(desiredType);
t
是在运行时计算的类型对象 ; 您不能在C#编译器期望编译时类型为name的地方使用它。 编译器给您该错误,因为它找不到文字名称为“ t”的类型。
但是哈克,尽管还不那么简单,您仍然可以做自己想做的事情:
var t = currentProperty.PropertyType;
var genericType = typeof(MyClass<>).MakeGenericType(t);
var x = Activator.CreateInstance(genericType);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.