【问题标题】: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.String 和System.Int32 仍然没有成功。
  • 看起来答案是对 CLR 内部的神奇调用(不太令人惊讶):stackoverflow.com/questions/5056788/object-gettype-source-code
  • @EdPlunkett 一定是这样。由于GeType() 是extern,它没有方法体,因此null 值

标签: c# .net reflection types


【解决方案1】:

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

来自 C# 规范 10.6.7

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

Here 的详细回答。

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2020-04-18
    • 1970-01-01
    • 2020-04-12
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多