"typeof"如何工作? [英] How does 'typeof' work?

查看:64
本文介绍了"typeof"如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇C#中typeof的方法体"是什么样子(很确定我不能在反射器中找到它,因为它是关键字而不是方法).

I am curious what the "method body" for typeof in C# would look like (pretty sure I can't get to it in reflector as it's a keyword not a method).

我猜想它等同于GetType(将符号魔术转换为字符串).

I am guessing it is equivalent to GetType(magic convert symbol to string).

在Reflector中查看GetType(string),它调用方法"PrivateGetType",该方法调用"RuntimeTypeHandle.GetTypeByName",并且RuntimeTypeHandle似乎在类型背后有很多逻辑,但是GetTypeByName的内容未显示在Reflector中.

Looking at GetType(string) in Reflector it calls a method "PrivateGetType", which calls "RuntimeTypeHandle.GetTypeByName", and RuntimeTypeHandle seems to have a lot of the logic behind types in it, but the GetTypeByName stuff doesn't show up in Reflector.

推荐答案

如果您执行以下操作:

Type t = typeof(string);

然后,编译器将 typeof(string)位编译为

Then the compiler compiles the typeof(string) bit to a ldtoken MSIL instruction and then calls Type.GetTypeFromHandle to get an instance of the Type class.

Type.GetTypeFromHandle 由运行时实现(这就是为什么将其标记为"MethodImplOptions.InternalCall"属性的原因).您可以查看mono的源代码以了解其实际实现方式,但基本上您必须了解整个元数据系统,以了解 Type 和朋友在内部如何工作...

Type.GetTypeFromHandle is implemented by the runtime (which is why it's marked with the "MethodImplOptions.InternalCall" attribute). You can look at the source code to mono for how it's actually implemented, but you basically have to understand the whole metadata system to understand how Type and friends works internally...

这篇关于"typeof"如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆