简体   繁体   English

如何仅对一个班级的3个孩子实施一种非静态方法?

[英]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”类的类:

  • Base 基础
  • Class1 : Base 类别1:基地
  • Class2 : Base 类别2:基地
  • ... ...
  • Class7 : Base 类别7:基地

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 : 编辑:我不能这样:

  • Base 基础
    • Class with 'secret' method : Base 具有“秘密”方法的类:基础
    • Class1 : Class with 'secret' method Class1:具有“秘密”方法的类
    • Class2 : Class with 'secret' method Class2:具有“秘密”方法的类
    • Class3 : Class with 'secret' method Class3:具有“秘密”方法的类
    • Class4 : Base 类别4:基地
    • Class5 : Base 类别5:基地
    • Class6 : Base 类别6:基地
    • Class7 : Base 类别7:基地

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: 这样做:

  • Base 基础
    • Class with 'secret' method : Base 具有“秘密”方法的类:基础
      • Class1 : Class with 'secret' method Class1:具有“秘密”方法的类
      • Class2 : Class with 'secret' method Class2:具有“秘密”方法的类
      • Class3 : Class with 'secret' method Class3:具有“秘密”方法的类
    • Class4 : Base 类别4:基地
    • Class5 : Base 类别5:基地
    • Class6 : Base 类别6:基地
    • Class7 : Base 类别7:基地

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM