【问题标题】:calling child class method from base class C#从基类 C# 调用子类方法
【发布时间】:2016-10-05 16:14:14
【问题描述】:

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

代码示例如下:

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

【问题讨论】:

  • 只能通过反射或先将基类型转换为子类型。
  • 我在实现工厂方法模式时遇到了这个问题。根据条件,子类被实例化并分配给父类引用。但它只指父成员。那么我如何使方法调用泛型,以根据某些条件返回适当的子类对象?

标签: c# inheritance polymorphism


【解决方案1】:

实际上,您已经创建了 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"; 

【讨论】:

  • 那么在代码中的某个时刻,我们需要根据工厂方法中使用的相同条件强制转换父对象时,创建基类有什么好处?
  • @Tisha Anand:如果你必须cast,那没有任何好处。但通常我们不需要强制转换:我们可能想要的只是一个正确实现的Property1(在这种情况下应该是virtual甚至是abstract)在Parent 类中声明。
  • 感谢 Dmirty :) 所以我理解...如果子类有许多特定属性,那么除了在父类中将这些属性声明为虚拟或抽象之外,我们还可以使用强制转换运算符来设置子类类的个别属性。如果我错了,请纠正我。
  • @Tisha Anand:你说得对,如果特定属性很少,你可以使用 cast;但是过多的强制转换会使代码不可读,在这种情况下(子类彼此之间太不同)你可能不得不限制工厂方法。
猜你喜欢
  • 2011-01-05
  • 1970-01-01
  • 2011-01-22
  • 2018-10-15
  • 1970-01-01
  • 2013-03-22
  • 2015-03-30
  • 2012-06-28
  • 2017-12-13
相关资源
最近更新 更多