C#, access child properties from parent reference?

强颜欢笑 提交于 2020-01-11 11:28:25

问题


public void GetProps(Parent p){

   // want to access lots of child properties here
   string childProp1 = p.prop1;
   bool childProp2 = p.prop2;
   bool childProp3 = p.prop3;

}

However compiler complains that

"Parent does not contain definition prop1"

The function would take in different subtypes of Class Parent.

All the subclasses have this

public override string prop1 { get; set; }

Is there a way of accomplishing this?

EDIT: To make the question clearer

I current have a giant if-elseif where i do something like

if(p is Child0){
      Child0 ch = p as Child0; 

       // want to access lots of child properties here
       string childProp1 = ch.prop1;
       bool childProp2 = ch.prop2;
       bool childProp3 = ch.prop3;

}else if(p is Child1){
      Child1 ch = p as Child1; 

       // want to access lots of child properties here
       string childProp1 = ch.prop1;
       bool childProp2 = ch.prop2;
       bool childProp3 = ch.prop3;

}else if(...// and many more 

Now I wanted to remove all the redundant code and make one function that can handle all this.


回答1:


If all child classes need to have the properties (but with different implementations), you should declare them as abstract properties in the base class (Parent), then implement them in the child classes.

If some derived classes won't have those properties, then what would you expect your current GetProps to do?

EDIT: If you're using C# 4 and you definitely can't get a better class design (where the parent class declares the property) you could use dynamic typing:

public void GetProps(Parent p) {
    dynamic d = p;
    string childProp1 = d.prop1;
    bool childProp2 = d.prop2;
    bool childProp3 = d.prop3;
    // ...    
}

I'd treat this as a last resort though...




回答2:


As I understood from your question, you want to access Children Class members from object of Parent Class.

This behavior is not allowed in OOP. One way can be as suggested by Jon Skeet to create a Abstract base class and implement the required members in Children Classes.

Other way round can be to assign the required values to members of base class in derived class constructor using base construct. I do not know this will solve your problem or not. But Consider the following snippet for example:

 public class BaseClass
{
    public string FirstName = "Base Class";
    public string LastName = "Base Class";
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        base.LastName = "Derived Class";
    }
}

internal class Tester
{
    private static void Main(string[] args)
    {
        BaseClass objBaseClass = new BaseClass();
        Console.WriteLine("First Name : " + objBaseClass.FirstName);
        Console.WriteLine("Last Name : " + objBaseClass.LastName);

        DerivedClass objDerivedClass = new DerivedClass();
        Console.WriteLine("First Name : " + objDerivedClass.FirstName);
        Console.WriteLine("Last Name : " + objDerivedClass.LastName);

        BaseClass objBaseDerivedClass = new DerivedClass();
        Console.WriteLine("First Name : " + objBaseDerivedClass.FirstName);
        Console.WriteLine("Last Name : " + objBaseDerivedClass.LastName);

        Console.ReadKey();
    }
}

O/P First Name : Base Class

Last Name : Base Class

First Name : Base Class

Last Name : Derived Class

First Name : Base Class

Last Name : Derived Class

Let me know, if it helps out.




回答3:


The solution in case someone need it, it is just to cast the class you receive as a reference as follows:

public void GetProps(Parent p){
..
  string childProp1 = ((ChildClass)p).prop1;   
...
}



回答4:


If the property is defined in an intermediate class between parent and child and you don't have a reference to that intermediate class at design time then you could use reflection to get the property. But it sounds like you should be using the most relevant sub parent instead of simply parent.




回答5:


If I understood you correctly (- I'm assuming Parent is a base class from which Child0 Child1 etc inherit.) – you're just missing a declaration of prop1 in the parent. It won't get in the way, it will simply be overridden.

Check out this example (which returns "child string") and note that child is passed to a method that expects a ParentClass instance.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ChildClass child = new ChildClass();
        Text = ParentClass.mymethod(child);
    }
}

class ParentClass
{
    public virtual string s { get { return "parent string"; }  }

    public static string mymethod(ParentClass parent)
    {
        return parent.s;
    }
}

class ChildClass : ParentClass
{
    public override string s { get { return "child string"; }  }
}


来源:https://stackoverflow.com/questions/10370645/c-access-child-properties-from-parent-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!