简体   繁体   English

获取派生类以实现属性的最佳实践?

[英]Best practice for getting a derived class to implement a property?

Given a simple class hierarchy where each class is derived from an abstract base class. 给定一个简单的类层次结构,其中每个类都从抽象基类派生。 Every derived class will need to somehow provide an enum "value" which the base class will use in certain base methods. 每个派生类都需要以某种方式提供枚举“值”,基类将在某些基本方法中使用该枚举“值”。
eg 例如

Base class: 基类:

public abstract class AbstractFoo
{
  bool SaveFoo()
  {
    switch (BarType){...}
  }

}

and derived classes 和派生类

public class BananaFoo:AbstractFoo
{
  //barttype = fruit;
}

public class WhaleFoo:AbstractFoo
{
  //barttype = mammal;
}

There are a number of ways I can make sure that ALL classes derived from AbstractFoo implement a property "enum BarType" 我可以通过多种方法来确保从AbstractFoo派生的所有类都实现属性“ enum BarType”

public abstract BarType BarType{get;}

In each derived class I can then implement BarType to return the correct type, or add an abstract method to do a very similar thing. 然后,在每个派生类中,我可以实现BarType以返回正确的类型,或者添加抽象方法来执行非常相似的操作。

public BarType BarType{get{return _bartype;}}

OR add a concrete method to return a field - then I need to remember to add the field, but it's a lot less typing (C&P)? 还是添加一个具体的方法来返回一个字段-那么我需要记住要添加该字段,但是键入(C&P)少了很多?

What is the recommended way to do this? 推荐的方法是什么?

Another option is to force derived classes to pass a value of Foo to the base class: 另一个选择是强制派生类将Foo的值传递给基类:

public abstract class A {
  private readonly BarType _foo;

  protected A(BarType foo) {
    _foo = foo;
  }

  // Does Foo need to be public or is it only used internally by A?
  public BarType Foo { get { return _foo; } }
}

public class B : A {

  public B() : base(BarType.Value1) {
  }
}

I can't comment on what the correct way to do this is, but I've always used an abstract property on the base type (to force implementation), and then returned a constant from the subtype property. 我无法评论执行此操作的正确方法,但是我一直在基类型上使用抽象属性(以强制实施),然后从子类型属性返回常量。

for example: 例如:

public BarType BarType{get{return BarType.WhaleFoo ;}}

Assuming you're only returning a single value of the enum for each child class, the best way I know of is to implement an abstract property in the base class, then implement it in each child class. 假设您只为每个子类返回一个枚举值,那么我所知道的最好方法是在基类中实现一个抽象属性,然后在每个子类中实现它。

public abstract class A {
    public BarType Foo;

    public enum BarType {
        Value1,
        Value2
    }
}

public class B : A {
    public BarType Foo { get { return BarType.Value1; } }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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