这当然很简单,但困扰了我一段时间,所以希望在这里得到一些详细的解释。我知道当你这么做
BaseClass b = new DeriveClass();b的类型仍然是BaseClass而不是DeriveClass,因为从派生类到基类的隐式强制转换。
BassClass b = (BaseClass)new DeriveClass();但是编译器不需要这样做。无论如何,我不明白的是,当我试图调用b.GetType()时,它返回的是DriveClass而不是BaseClass。
为什么会这样呢?
发布于 2014-09-20 20:05:36
GetType()总是返回实例的当前类型(在运行时检查,而不是编译时间)。它写在msdn上:
获取当前实例的类型。
msdn上的代码示例:
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());
// The example displays the following output:
// mybase: Type is MyBaseClass
// myDerived: Type is MyDerivedClass
// object o = myDerived: Type is MyDerivedClass
// MyBaseClass b = myDerived: Type is MyDerivedClass https://stackoverflow.com/questions/25952798
复制相似问题