为啥我无法获取 GetType() 的 MethodBody?

Posted

技术标签:

【中文标题】为啥我无法获取 GetType() 的 MethodBody?【英文标题】:Why can't I get the MethodBody of GetType()?为什么我无法获取 GetType() 的 MethodBody? 【发布时间】:2015-11-04 18:29:04 【问题描述】:

假设我有这条线:

MethodBody getTypeMethod = typeof(object).GetMethod("GetType").GetMethodBody();
// getTypeMethod is null

为什么getTypeMethod 为空?如何获取GetType()方法的MethodBody

【问题讨论】:

您是否尝试过 System.Object 以外的其他内容? @StingyJack 是的,尝试使用System.StringSystem.Int32 仍然没有成功。 看起来答案是对 CLR 内部的神奇调用(不太令人惊讶):***.com/questions/5056788/object-gettype-source-code @EdPlunkett 一定是这样。由于GeType()extern,它没有方法体,因此null 【参考方案1】:

您自己得到了答案,但只是为了确认,Object.GetType() 是一个外部方法,而外部方法没有指定方法体。

来自 C# 规范 10.6.7

当方法声明包含 extern 修饰符时,该方法是 据说是外部方法。外部方法已实现 在外部,通常使用 C# 以外的语言。因为一个 外部方法声明不提供实际实现, 外部方法的方法体只包含一个分号。

Here 的详细回答。

【讨论】:

以上是关于为啥我无法获取 GetType() 的 MethodBody?的主要内容,如果未能解决你的问题,请参考以下文章