![](/img/trans.png)
[英]C# Inheritance: How to invoke the base class constructor when i call the derived class constructor
[英]How and when to call the base class constructor in C#
如何以及何時在C#中調用基類構造函數
您可以像這樣調用基類構造函數:
// Subclass constructor
public Subclass()
: base()
{
// do Subclass constructor stuff here...
}
如果存在所有子類需要設置的內容,則可以調用基類。 需要初始化的對象等...
希望這可以幫助。
從子類構造函數中調用基類構造函數通常是一種很好的做法,以確保基類在子類之前初始化自身。 您使用base
關鍵字來調用基類構造函數。 請注意,您還可以使用this
關鍵字在類中調用另一個構造函數。
以下是如何執行此操作的示例:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.