简体   繁体   中英

Casting to a Generic Typed Object Using Reflection

如果在运行时之前不知道T是什么,是否可以使用反射将对象从类型objectMyType<T>

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.

The trick in such situations, is to use a non-generic class with generic methods.

public class MyType
{
    public T GetResult<T>() {
    }
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM