C#,从父级引用访问子级属性? [英] 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;
}
但是编译器抱怨
父级不包含prop1定义"
"Parent does not contain definition prop1"
该函数将采用Class Parent的不同子类型.
The function would take in different subtypes of Class Parent.
所有子类都有这个
public override string prop1 { get; set; }
有没有办法做到这一点?
Is there a way of accomplishing this?
为了使问题更清楚
我目前有一个巨大的if-elseif,我在其中做类似的事情
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.
推荐答案
如果 all 子类需要具有属性(但实现方式不同),则应将其声明为 abstract 基类(Parent
)中的属性,然后在子类中实现它们.
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.
如果某些派生类没有这些属性,那么您希望当前的GetProps
做什么?
If some derived classes won't have those properties, then what would you expect your current GetProps
to do?
如果使用的是C#4,并且绝对无法获得更好的类设计(父类声明该属性),则可以使用动态类型输入:
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...
这篇关于C#,从父级引用访问子级属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!