Gọi child class method từ base class C#

Khi khai báo một lớp con kế thừa phương thức từ lớp cha, bạn muốn gọi method từ lớp con với khai báo trừu tượng nhưng trong lớp cha không có, hãy xem ví dụ mình lấy trên stackoverflow.

Ví dụ

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

Actually you´ve created a Child1 and Child2 instances, so you can cast to them:
  Parent p1 = new Child1();
  Parent p2 = new Child2();

  // or ((Child1) p1).Child1Property = "hi";
  (p1 as Child1).Child1Property = "hi";
  (p2 as Child2).Child2Property = "hello";
To check if cast successful, test for null:
  Child1 c1 = p1 as Child1;

  if (c1 != null)
    c1.Child1Property = "hi";
A better design, however, is assign to Child1 and Child2 local variables
   Child1 p1 = Child1(); 
   p1.Child1Property = "hi"; 
Post a Comment