0

我有一个基类:

class B { }

它有很多依赖项:

public B(IFoo foo, IBar bar, IFooBar fooBar, IAlice alice, IBob bob) { }

我有很多看起来像这样的派生类:

public class D : B { }

但是它们需要满足 的构造函数B,所以它们有依赖关系:

public D(IFoo foo, IBar bar, IFooBar fooBar, IAlice alice, IBob bob)
    : base(foo, bar, fooBar, alice, bob) { }

就像我说的,我有很多这样的。这似乎很糟糕。它是重复的。单个代码更改会影响B许多类,而这些类都需要一个小的、无聊的更改。

帮助?

4

1 回答 1

2

I would look at what changes you're making to B and if they're indicative of needing an extra subclass that most subclasses of B SHOULD subclass.

Having lots of constructor arguments isn't really a problem, just an inconvenience. You may wish to make a class to store all the base class arguments. When you need an instance of D, populate an instance of it and then pass that to D, which will then pass it to B and extract all its data.

public Bargs(IFoo foo, IBar bar, IFooBar fooBar, IAlice alice, IBob bob) { }
public B(Bargs myArgs){}
public D(Bargs myArgs) : B(myArgs){}
于 2013-02-12T03:23:46.907 回答