在构造函数中自动调用超类方法

时间:2012-10-27 23:43:27

标签: c# .net

在C#中是否有办法保证每个子类构造函数都会自动调用超类的方法?

具体来说,我正在寻找一种只向超类添加代码的解决方案,所以不是“base(arguments)”

1 个答案:

答案 0 :(得分:5)

保证它的唯一方法是在基类的构造函数中进行调用。由于所有子类都必须调用基类的构造函数,因此也会调用您感兴趣的方法:

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) {
    }
}