从基类C#调用子类方法

时间:2016-06-06 06:35:00

标签: c# inheritance polymorphism

是否可以从基类引用中调用子类方法?请建议......

代码示例如下:

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";
    }
}

1 个答案:

答案 0 :(得分:8)

实际上您已经创建了Child1Child2个实例,因此您可以投射给他们:

  Parent p1 = new Child1();
  Parent p2 = new Child2();

  // or ((Child1) p1).Child1Property = "hi";
  (p1 as Child1).Child1Property = "hi";
  (p2 as Child2).Child2Property = "hello";

要检查投射是否成功,请测试null

  Child1 c1 = p1 as Child1;

  if (c1 != null)
    c1.Child1Property = "hi";

然而,更好的设计会分配给Child1Child2局部变量

   Child1 p1 = Child1(); 
   p1.Child1Property = "hi";