[英]How to implement one non-static method for only 3 children of a class?
I have 7 classes which inherit the "Base" class : 我有7个继承“ Base”类的类:
For 3 of these 7 classes, I have to add a non-static method (exactly the same code), but this method should not be visible for the others classes, and I don't know how to organize my code. 对于这7个类中的3个,我必须添加一个非静态方法(完全相同的代码),但是该方法对于其他类不可见,并且我不知道如何组织代码。
Anybody can help me ? 有人可以帮助我吗?
Edit : I can't do like this : 编辑:我不能这样:
Because in the non-static method, I use an attribute which is declared in the Class1, Class2 and Class3 classes (and I can't move it, it's handled by Entity Framework). 因为在非静态方法中,我使用在Class1,Class2和Class3类中声明的属性(而且我无法移动它,它由Entity Framework处理)。 Example : 范例:
this.var
Do it like so: 这样做:
There are more ways to reuse code than inheritance. 重用代码的方法比继承多。 Inheritance should only be used when you need an "is-a" type, not simply because you don't want multiple copies of code. 继承仅应在需要“ is-a”类型时使用,而不仅仅是因为您不需要多个代码副本。
Containment might be a better choice. 遏制可能是一个更好的选择。 But, it depends on what exactly your method does. 但是,这取决于您的方法到底要做什么。
For instance: 例如:
public class Contained {
public void SpecialMethod() {}
}
public class Class1 : Base {
private Contained _contained = new Contained();
public override void NormalMethod() {
// do some work
_contained.SpecialMethod();
}
}
public class Class2 : Base {
private Contained _contained = new Contained();
public override void NormalMethod() {
// do some work
_contained.SpecialMethod();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.