C#父类引用指向子类实例:typeof返回值及实际类型判断方法
在C#中父类引用指向子类实例时typeof的行为及实际类型获取方法
首先明确核心规则:
- typeof操作符是编译时确定结果的,它返回的是变量声明类型的Type对象,和实际指向的实例类型完全无关。
- 你给出的代码存在两处语法错误:
typeOf应为大写开头的typeof;判断时要和typeof(Child)/typeof(Parent)比较,而不能直接写类型名。
修正后的示例代码:
Parent c = new Child(); // typeof(c) 等价于 typeof(Parent),因为c的声明类型是Parent if (typeof(c) == typeof(Child)) Console.WriteLine("c is stored as a Child"); else if (typeof(c) == typeof(Parent)) Console.WriteLine("c is stored as a Parent");
这段代码会输出c is stored as a Parent,因为typeof只关注变量的声明类型,不识别实际实例的子类类型。
如果要获取对象的真实子类类型,需要使用实例方法**GetType()**,它会返回运行时对象的实际类型:
Parent c = new Child(); if (c.GetType() == typeof(Child)) Console.WriteLine("c is actually a Child instance"); else if (c.GetType() == typeof(Parent)) Console.WriteLine("c is actually a Parent instance");
这段代码会输出c is actually a Child instance,因为GetType()会精准识别到实际创建的是Child类的实例。
额外补充:如果只是想判断实例是否属于某个类型(含子类),用is关键字写法更简洁:
if (c is Child) Console.WriteLine("c is a Child instance");
内容的提问来源于stack exchange,提问作者Aceroy
相关产品推荐
相关产品推荐

