【发布时间】:2016-10-05 16:14:14
【问题描述】:
是否可以从基类引用中调用子类方法?请建议...
代码示例如下:
public class Parent
{
public string Property1 { get; set; }
}
public class Child1:Parent
{
public string Child1Property { get; set; }
}
public class Child2 : Parent
{
public string Child2Property { get; set; }
}
public class Program
{
public void callMe()
{
Parent p1 = new Child1();
Parent p2 = new Child2();
//here p1 & p2 have access to only base class member.
//Is it possible to call child class memeber from the base class reference based on the child class object it is referring to?
//for example...is it possible to call as below:
//p1.Child1Property = "hi";
//p2.Child1Property = "hello";
}
}
【问题讨论】:
-
只能通过反射或先将基类型转换为子类型。
-
我在实现工厂方法模式时遇到了这个问题。根据条件,子类被实例化并分配给父类引用。但它只指父成员。那么我如何使方法调用泛型,以根据某些条件返回适当的子类对象?
标签: c# inheritance polymorphism