c# - 为什么 System.Exception 影子 GetType()

标签 c# .net reflection gettype

在尝试比较两个 dll 的 API 更改时,一位同事注意到某些类有两个 GetType() 方法。

经过更深入的检查,结果是 System.Exception 隐藏了 GetType():

// this method is required so Object.GetType is not made virtual by the compiler
public new Type GetType() 
{
  return base.GetType(); 
}

我看到 System.Exception 实现了 _Exception,但我没有看到必须显式隐藏 GetType 的原因,因为它无论如何都不是虚拟的。

那么为什么 System.Exception 会影响 GetType()?

最佳答案

我不确定它是否与 shriek 提到的 COM 有任何关系,但它肯定与不使 Object.GetType() 虚拟化有关。

shriek 的回答中的第二个链接暗示了它,但是 this answer to another question让它更清楚:

The CLR requires that all methods that implement an interface method must be virtual (Ecma 335 Partition II Section 12.1).

  • If the method in the base class is not virtual, but in the same assembly, the sneaky compiler actually makes it virtual and final.

如果 System.Exception 没有隐藏 GetType(),Object 的 GetType() 实现将被编译器自动转换为虚方法。

关于c# - 为什么 System.Exception 影子 GetType(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16719504/

相关文章:

C# 将图像转换为完全黑白

c# - 是否在 ASP.Net 应用程序中锁定单例公共(public)方法

C# 嵌入式 FTP 服务器

c# - 在 Windows 服务中持久化变量的公认方法是什么

.net - mscorlib.dll 和 System.dll

c# - 在 Sitemanager->Administrations->Users 添加自定义选项卡

.net - 各种 .NET 依赖注入(inject)框架的比较(优缺点)

c# - 使用反射和结构图

.net - Powershell 从字符串中生成 System.Type

reflection - Mathematica 中的命令完成 : suggest rules/options