如果我直到运行时才知道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.
更多推荐
发布评论