Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know it's not possible to inherit constructors in C#, but there's probably a way to do what I want to do.

I have a base class that is inherited by many other classes, and it has an Init method that does some initializing taking 1 parameter. All other inheriting classes also need this initializing, but I'd need to create separate constructors for all of them that would like like this:

public Constructor(Parameter p) {
    base.Init(p);
}

That totally violates the DRY principles! How can I have all necessary stuff initialized without creating dozens of constructors?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't need to create loads of constructors, all with the same code; you create only one, but have the derived classes call the base constructor:

public class Base
{
    public Base(Parameter p)
    {
        Init(p)
    }

    void Init(Parameter p)
    {
        // common initialisation code
    }
}

public class Derived : Base
{
    public Derived(Parameter p) : base(p)
    {
 
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...