从基类中调用子类方法的C#实现

4

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

以下是代码示例:

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

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

9
实际上你已经创建了Child1Child2的实例,所以你可以对它们进行类型转换:
  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";

然而,更好的设计是为Child1Child2分配本地变量。

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

那么,当在代码的某个点上,我们需要根据工厂方法中使用的相同条件强制转换父对象时,创建基类的好处是什么? - Tisha Anand
@Tisha Anand:如果你必须进行强制转换,那么就没有任何好处。但通常我们不需要进行强制转换:我们可能只是想要一个正确实现的Property1(在这种情况下应该是虚拟或甚至抽象的),它在Parent类中被声明。 - Dmitry Bychenko
谢谢Dmirty :) 我的理解是,如果子类有许多特定属性,则除了在父类中将这些属性声明为虚拟或抽象外,我们还可以使用强制转换运算符来设置子类的个别属性。如果我理解有误,请纠正我。 - Tisha Anand
@Tisha Anand:你说得对,在某些特定属性的情况下,可以使用强制转换;但是过多的强制转换会使代码变得难以阅读,在这种情况下(子类之间差异太大),你可能需要避免使用工厂方法。 - Dmitry Bychenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接