How and when to call the base class constructor in C#
How and when to 开发者_运维知识库call the base class constructor in C#
You can call the base class constructor like this:
// Subclass constructor
public Subclass()
: base()
{
// do Subclass constructor stuff here...
}
You would call the base class if there is something that all child classes need to have setup. objects that need to be initialized, etc...
Hope this helps.
It's usually a good practice to call the base class constructor from your subclass constructor to ensure that the base class initializes itself before your subclass. You use the base
keyword to call the base class constructor. Note that you can also call another constructor in your class using the this
keyword.
Here's an example on how to do it:
public class BaseClass
{
private string something;
public BaseClass() : this("default value") // Call the BaseClass(string) ctor
{
}
public BaseClass(string something)
{
this.something = something;
}
// other ctors if needed
}
public class SubClass : BaseClass
{
public SubClass(string something) : base(something) // Call the base ctor with the arg
{
}
// other ctors if needed
}
精彩评论