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

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

inheritance - C# - Making all derived classes call the base class constructor

I have a base class Character which has several classes deriving from it. The base class has various fields and methods.

All of my derived classes use the same base class constructor, but if I don't redefine the constructor in my derived classes I get the error:

Error: Class "child class" doesn't contain a constructor which takes this number of arguments

I don't want to redefine the constructor in every derived class because if the constructor changes, I have to change it in every single class which, forgive any misunderstanding, goes against the idea of only writing code once?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use the following syntax to call the base class constructor from the classes that derive from it:

public DerivedClass() : base() {
    // Do additional work here otherwise you can leave it empty
}

This will call the base constructor first, then it will perform any additional statements, if any, in this derived constructor.

Note that if the base constructor takes arguments you can do this:

public DerivedClass(int parameter1, string parameter2) 
    : base(parameter1, parameter2) {
    // DerivedClass parameter types have to match base class types
    // Do additional work here otherwise you can leave it empty
}

You can find more information about constructors in the following page:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors

In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...