使用类型 t 实例化类,如所反映的
我有以下代码。 t
在第二行显示为无效。
无法解析符号“t”
如何使用类型 t
实例化泛型类。
Type t = currentProperty.PropertyType;
var x = new MyClass<t>();
谢谢
I have the following code. t
is showing as invalid on the second line.
Cannot resolve symbol 't'
How can I instantiate a generic class using Type t
.
Type t = currentProperty.PropertyType;
var x = new MyClass<t>();
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
泛型只是编译时功能,而不是运行时功能。您需要使用反射创建该类。
Generics are only a compile time feature, not a runtime feature. You need to create the class using reflection.
t
是在运行时计算的类型object;您不能在 C# 编译器需要编译时类型 name 的地方使用它。编译器给你这个错误是因为它找不到带有文字名称“t”的类型。但是听着,你仍然可以做你想做的事,尽管不那么简单:
t
is a type object computed at run-time; you can't use it in a place where the C# compiler is expecting a compile-time type name. The compiler is giving you that error because it can't find a type with the literal name "t".But hark, you can still do what you want, albeit less simply: