C# 为什么System.Exception卷影GetType()

C# 为什么System.Exception卷影GetType(),c#,.net,reflection,gettype,C#,.net,Reflection,Gettype,在尝试比较两个DLL的API更改时,一位同事注意到有些类有两个GetType()方法 经过深入检查,发现System.Exceptionshadows GetType() 我看到System.Exceptionimplements\u Exception,但我看不出为什么GetType必须显式隐藏,因为它无论如何都不是虚拟的 那么,为什么System.Exception shadow GetType()?会在注释中查找“long”答案 简而言之,System.Exception实现了System

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

经过深入检查,发现
System.Exception
shadows GetType()

我看到
System.Exception
implements\u Exception,但我看不出为什么GetType必须显式隐藏,因为它无论如何都不是虚拟的

那么,为什么System.Exception shadow GetType()?

会在注释中查找“long”答案


简而言之,
System.Exception
实现了
System.Runtime.InteropServices.\u Exception
接口,它也有一个GetType方法,因此必须
new
-实现GetType方法。

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

shriek回答中的第二个链接暗示了这一点,但更为明确:

CLR要求实现接口方法的所有方法必须是虚拟的(第12.1节)

  • 如果基类中的方法不是虚拟的,而是在同一个程序集中,那么狡猾的编译器实际上会使它成为虚拟的和最终的

如果
System.Exception
没有对GetType()进行阴影处理,则对象的GetType()实现将由编译器自动转换为虚拟方法。

我不太清楚为什么它必须
新建
它。您可以创建一个实现
\u Exception
的类,而不隐藏GetType()。正如第二个链接中提到的,CLR似乎也没有自动实现它。这篇文章或许可以回答这个问题。另外,System.Type也是这样做的,并且还实现了一个com接口。是的-正是因为那篇文章,我发现了另一个StackOverflow问题。为什么会出现这个问题?我假设是出于性能原因
GetType()
将只实现一个(由CLR提供),那么为什么要在btable中添加一个新条目,为什么要导致虚拟方法的开销呢。
// this method is required so Object.GetType is not made virtual by the compiler
public new Type GetType() 
{
  return base.GetType(); 
}