来自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()方法和spoof
。
假设您可以重写该方法,除了返回实例的类型之外,您还希望它做什么。当您为每个类重写该方法以返回实例的类型时,那么您就不会违反DRY了。
关于c# - 为什么Object.GetType()不是虚拟的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3253329/