从基类C#调用子类方法

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

代码示例如下:

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

实际上你已经创建了一个Child2Child2实例,所以你可以Child2转换它们:

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

但是,更好的设计是分配给Child2Child2局部变量

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