简体   繁体   English

从基类C#调用子类方法

[英]calling child class method from base class C#

Is it possible to call child class method from base class reference? 是否可以从基类引用中调用子类方法? Please suggest... 请建议......

Code example is given below: 代码示例如下:

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: 其实......你创造了一个Child1Child2情况下,这样你就可以给他们:

  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 : 要检查是否成功 ,测试null

  Child1 c1 = p1 as Child1;

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

A better design, however, is assign to Child1 and Child2 local variables 更好的设计,然而,被分配到Child1Child2局部变量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM