开发者

How does 'typeof' work?

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).

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

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.


If you do something like:

Type t = 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 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜