简体   繁体   中英

Automatically call superclass method in constructor

Is there a way in C# to guarantee that a method of a superclass will be automatically called by every subclass constructor?

Specifically, I am looking for a solution that only adds code to the superclass, so not "base(arguments)"

The only way to guarantee it is to make the call in the constructor of the base class. Since all subclasses must call a constructor of the base, your method of interest will be called as well:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM