.NET Framework: Get Type from TypeInfo

左心房为你撑大大i 提交于 2020-01-02 02:23:46

问题


The new reflection API introduces the TypeInfo class: https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo(v=vs.110).aspx

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 its refering to? Can I just write

Type type = typeInfo.GetType();

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


回答1:


If you call typeInfo.GetType(), you will indeed get the execution-time type of the objec 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;


来源:https://stackoverflow.com/questions/43523510/net-framework-get-type-from-typeinfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!