c# - 为什么 Object.GetType() 不是虚拟的?

标签 c# .net architecture

取自 MSDN 的代码示例

public class Test {
public static void Main() {
  MyBaseClass myBase = new MyBaseClass();
  MyDerivedClass myDerived = new MyDerivedClass();
  object o = myDerived;
  MyBaseClass b = myDerived;

  Console.WriteLine("mybase: Type is {0}", myBase.GetType());
  Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
  Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
  Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());   }}

/*
This code produces the following output.
mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass 
*/

那么将 GetType() 设为虚拟是否合乎逻辑,至少它可以像虚拟一样工作?任何人都可以解释一下吗? 以及其他问题 NET 框架中是否有任何其他方法具有类似于 GetType 的行为?

最佳答案

因为 .Net 框架不希望您覆盖 GetType() 方法和关于类型的欺骗

假设您可以覆盖该方法,除了返回实例的类型之外,您还希望它做什么。当您覆盖每个类的方法以返回实例的类型时,您是否违反了 DRY。

关于c# - 为什么 Object.GetType() 不是虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253329/

相关文章:

architecture - Apache Karaf 和 A​​pache Commons bundle

android - 如何在Android的MVVM架构中将 Action 从View发送到ViewModel

node.js - 基于 Mongoose 的应用架构

c# - 实现IQueryable包装器来转换结果对象

c# - 休息不允许在 IIS 8.5 : error 405 中放置

c# - http工作时如何测试WCF net.tcp?

.net - SuspendLayout 和 BeginUpdate 的区别

c# - 如何使用 C# 创建带有粗体标题行的 csv 文件

c# - 帮助事件驱动的 TCP 服务器

.net - 在 .NET 中检索终端服务 session ID?