开发者

C#: How to use a derived class's const variable in base's constructor

Thanks in advance,

My situation is that I have an abstract class called Vehicle that holds:

private List<Tire> m_Tires;

The thing is that the number of tires in the list is determined in the derived classes and varies between one and another, but the code needed for the instantiation is the same and therefore I would highly prefer to avoid code duplication and place that code (that instantiates m_Tires) in the abstract Vehicle class's constructor.

I first thought of using protected abstract void initializeTires(); to be implemented in the derived classes and be called from Vehicle's constructor. I saw here it's bad programming and error prone.

So to make a long story short: Is it pos开发者_如何转开发sible to avoid the code duplication here or I'll just have to make peace with it?


You can create a protected constructor and chain it.


How about creating a:

initializeTires(int numberOfTyres); 

in the base class and call this with the correct parameter in the derived class.


@Oded and a example of that is

public abstract class MyAbstract {
   private List<Tire> m_Tires;

   protected MyAbstract(int count) {
      m_Tires = new List<Tire>(count);
   }
}

public class MyClass : MyAbstract {
   public MyClass(int count) : base(count) { }   
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜