継承されたクラスが基本クラスのコンストラクターパラメーターを渡さなければならないことを回避するにはどうすればよいですか?

パスカル

基本クラスと継承子クラスがあります。

基本クラスのコンストラクターは、子コンストラクターから渡したくないパラメーターを受け入れます。

パラメータはジェネリックです List<MyInterface>

それはC#で可能ですか?

現時点では、私の子クラスコンストラクターは次のようになっています。

public ChildClass() : base (new List<MyInterface>());

リストを新しくすることなく、より良い方法はありますか?

ハビブ

基本クラスのコンストラクターがパラメーターを予期している場合は、そのパラメーターを子クラスから渡す必要があります。

2つのオプションがあります。

  1. Define a parameterless constructor in base class and then you can avoid passing your parameter. (Based on comment from @aevitas, if you are going to follow that approach, you may define the parameterless constructor as protected, as that will only be available to child classes)

Like:

public class BaseClass
{
   public BaseClass() // or protected
   {
     //does nothing
   }
}

and then call it like:

public ChildClass() : base ();

or just

public ChildClass() //Since base() would be called implicitly. 
  1. The other option is what you are using now, You can pass a new empty instance of your list or null as per your requirement.

You should also revisit your design. Not having a parameterless constructor in the base class implies that the class object requires that particular parameter to to work. Working around it is a code smell.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ