Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...