使用反射投射到通用类型化对象(Casting to a Generic Typed Object Using Reflection)

编程入门 行业动态 更新时间:2024-10-27 20:32:48
使用反射投射到通用类型化对象(Casting to a Generic Typed Object Using Reflection)

如果我直到运行时才知道T是什么,才可以使用反射将对象从类型object为MyType<T> ?

Can I cast an object from type object to MyType<T> using reflection if I don't know what T is until runtime?

最满意答案

您不能在编译时转换为未知类型。 铸造实际上仅作为编译时构造有用,因为您需要知道该类型才能直接使用它。

如果你的目标是通过反射来处理对象,那么这是一个不同的场景。 在这种情况下,您可以使用Type.MakeGenericType为您的对象创建正确的类型。

这将允许您使用反射来处理您的对象。

You can't cast to a type unknown at compile time. Casting is really only useful as a compile-time construct, as you'd need to know the type in order to use it directly.

If your goal is to work with the object via Reflection, however, that's a different scenario. In that case, you can use Type.MakeGenericType to create the correct type for your object.

This will allow you to use reflection to work upon your object.

更多推荐

本文发布于:2023-07-21 11:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1209776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   对象   类型   Casting   Reflection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!