为什么Object.GetType()不是虚拟的?不是、Object、GetType

由网友(搅散一池星光)分享简介:$ C从MSDN采取$ C样品code sample taken from MSDNpublic class Test {public static void Main() {MyBaseClass myBase = new MyBaseClass();MyDerivedClass myDerived = ne...

$ C从MSDN采取$ C样品

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()虚拟的,至少它可以作为虚拟?任何人都可以explaine吗? 而另一个问题是,在.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 Framework并不是要你覆盖的GetType()方法,恶搞有关类型

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

假设你可以忽略什么,你会希望它不是返回的实例的类型做其他的方法。当你重写方法为每个类返回的实例的类型,你不违反干呢。

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.

阅读全文

相关推荐

最新文章