使用反射转换为通用类型对象
如果我直到运行时才知道 T 是什么,我可以使用反射将对象从 object
类型转换为 MyType
吗?
Can I cast an object from type object
to MyType<T>
using reflection if I don't know what T is until runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,技巧是使用具有泛型方法的非泛型类。
但请注意,这发生在编译时。泛型让您有机会在编译时创建不同“风格”的类型或方法;但泛型不是动态的!泛型是类型安全的,类型安全只能在编译时实现(因为是编译器检查类型安全)。
The trick in such situations, is to use a non-generic class with generic methods.
Note, however, that this happens at compile time. Generics give you the opportunity to create different "flavors" of a type or a method at compile time; but generics are not dynamic! Generics are type-safe and type safety can only be achieved at compile time (because it's the compiler who checks the type safety).
您无法在编译时强制转换为未知类型。强制转换实际上仅作为编译时构造有用,因为您需要知道类型才能直接使用它。
但是,如果您的目标是通过反射处理对象,那就是不同的情况了。在这种情况下,您可以使用 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.