在尝试比较两个 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/