简体   繁体   中英

Does typeof(myType).TypeHandle use reflection?

If I wrote this code:

typeof(myType).TypeHandle 

Would it use reflection?

How much different from:

Type.GetType(string).TypeHandle

is it?

Well, it really depends on what you mean by "reflection" - which isn't exactly strictly defined.

There are two parts to using typeof in the compiled code. The first is the use of the ldtoken which is an IL instruction described like this in the CIL spec:

The ldtoken instruction pushes a RuntimeHandle for the specified metadata token. The token shall be one of:

  • A methoddef, methodref or methodspec: pushes a RuntimeMethodHandle
  • A typedef, typeref, or typespec : pushes a RuntimeTypeHandle
  • A fielddef or fieldref : pushes a RuntimeFieldHandle
The value pushed on the stack can be used in calls to reflection methods in the system class library

After this, a call to Type.GetTypeFromHandle is made.

This is all significantly quicker than Type.GetType(string) however, if that's what you were concerned with.

EDIT: I just noticed the TypeHandle part of your question. As far as I can see, the MS compiler doesn't optimise away the call to GetTypeFromHandle and then TypeHandle, even though I guess you really only need the ldtoken call.

Whether all of this counts as "reflection" or not is up to you...

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