typeof(myType).TypeHandle是否使用反射?
时间:2020-03-06 15:05:29 来源:igfitidea点击:
如果我写了这段代码:
typeof(myType).TypeHandle
它会使用反射吗?
与以下内容有何不同?
Type.GetType(string).TypeHandle
是吗?
解决方案
好吧,这实际上取决于我们对"反射"的含义,而"反射"没有严格定义。
在编译后的代码中使用typeof
有两部分。首先是使用ldtoken,这是一条CIL规范中描述的IL指令:
The ldtoken instruction pushes a RuntimeHandle for the specified metadata token. The token shall be one of: A methoddef, methodref or methodspec: pushes a RuntimeMethodHandleA typedef, typeref, or typespec : pushes a RuntimeTypeHandleA 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
之后,调用Type.GetTypeFromHandle
。
但是,如果我们担心的是,这都比Type.GetType(string)
快得多。
编辑:我只是注意到问题的TypeHandle部分。据我所知,即使我真的只需要ldtoken调用,MS编译器也不会优化对GetTypeFromHandle和TypeHandle的调用。
是否将所有这些都视为"反射"取决于我们...