简体   繁体   中英

.NET Framework: Get Type from TypeInfo

The new reflection API introduces the TypeInfo class:
https://docs.microsoft.com/en-us/dotnet/api/system.reflection.typeinfo

I can get a TypeInfo instance of a Type (say, a Car ) by writing

TypeInfo typeInfo = typeof(Car).GetTypeInfo();

Now, what if I just have a TypeInfo instance? How do I get the Type it's referring to? Can I just write

Type type = typeInfo.GetType();

Or will this return a type that is equal to typeof(TypeInfo) ?

If you call typeInfo.GetType() , you will indeed get the execution-time type of the object that typeInfo refers to - so some concrete type derived from TypeInfo .

You want TypeInfo.AsType() :

Returns the current type as a Type object.

So your code would be:

Type type = typeInfo.AsType();

Or, as noted in comments, something I'd never noticed: TypeInfo derives from Type ! So just use:

Type type = typeInfo;

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