Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

inheritance - C#, access child properties from parent reference?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...