c# - 从基类 C# 调用子类方法

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

最佳答案

实际上您已经创建了一个 Child1Child2 实例,因此您可以强制转换给它们:

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

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

要检查 cast 是否成功,请测试 null:

  Child1 c1 = p1 as Child1;

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

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

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

关于c# - 从基类 C# 调用子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37650911/

相关文章:

java - 这真的是动态多态吗?当我们使用 new 操作符实例化一个类时,编译器可以获得哪些信息?

c# - 将 javascript 对象转换为相应的 C# 字典所需的帮助

c# - 将对象转换为非显式实现的接口(interface)

c# - 如何检测用户何时单击 WebView 控件中的超链接?

c++ - static_assert 向上转换是否需要调整指针

c# - 如何判断一个类型是否在继承层次中

java - mongoTemplate.save() 一个抽象类

c++ - 如何使用多态参数动态调用函数

c# - 具有依赖注入(inject)的 AutoMapper 不映射配置文件?

c# - RegAsm.exe 和 regsvr32 有什么区别?如何使用 regsvr32 生成 tlb 文件?