为什么 Object.GetType() 不是虚拟的? [英] why Object.GetType() is not virtual?

查看:34
本文介绍了为什么 Object.GetType() 不是虚拟的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 MSDN 的代码示例

code sample taken from 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 的行为?

So would it be logical to make GetType() virtual at least it works as virtual? Can anybody explaine that? And other question Is any other methods in NET framework which have behaviour alike GetType?

推荐答案

因为 .Net 框架不希望你重写 GetType() 方法和关于类型的 spoof.

because .Net framework does not want you to override the GetType() method and spoof about the type.

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

assume you can override the method what else would you want it to do other than returning the type of the instance. and when you override the method for each of your classes to return the type of the instance, won't you violate DRY then.

这篇关于为什么 Object.GetType() 不是虚拟的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆