使用类型 t 实例化类,如所反映的

发布于 2024-12-29 19:44:41 字数 218 浏览 2 评论 0原文

我有以下代码。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏爱自由 2025-01-05 19:44:41

泛型只是编译时功能,而不是运行时功能。您需要使用反射创建该类。

Type t = currentProperty.PropertyType;
Type desiredType = typeof(MyClass<>).MakeGenericType(t);
var instance = Activator.CreateInstance(desiredType);

Generics are only a compile time feature, not a runtime feature. You need to create the class using reflection.

Type t = currentProperty.PropertyType;
Type desiredType = typeof(MyClass<>).MakeGenericType(t);
var instance = Activator.CreateInstance(desiredType);
软糯酥胸 2025-01-05 19:44:41

t 是在运行时计算的类型object;您不能在 C# 编译器需要编译时类型 name 的地方使用它。编译器给你这个错误是因为它找不到带有文字名称“t”的类型。

但是听着,你仍然可以做你想做的事,尽管不那么简单:

var t = currentProperty.PropertyType;
var genericType = typeof(MyClass<>).MakeGenericType(t);
var x = Activator.CreateInstance(genericType);

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:

var t = currentProperty.PropertyType;
var genericType = typeof(MyClass<>).MakeGenericType(t);
var x = Activator.CreateInstance(genericType);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文