スーパークラスのメソッドがすべてのサブクラスコンストラクターによって自動的に呼び出されることを保証する方法はC#にありますか?
具体的には、「base(arguments)」ではなく、スーパークラスにコードを追加するだけのソリューションを探しています。
それを保証する唯一の方法は、基本クラスのコンストラクターで呼び出しを行うことです。すべてのサブクラスはベースのコンストラクターを呼び出す必要があるため、対象のメソッドも呼び出されます。
class BaseClass {
public void MethodOfInterest() {
}
// By declaring a constructor explicitly, the default "0 argument"
// constructor is not automatically created for this type.
public BaseClass(string p) {
MethodOfInterest();
}
}
class DerivedClass : BaseClass {
// MethodOfInterest will be called as part
// of calling the DerivedClass constructor
public DerivedCLass(string p) : base(p) {
}
}