[英]How to call base class constructor in derived class?
基於一些需求,我想將基類的所有構造函數/方法都添加到派生類中,而無需在派生類中編寫方法/構造函數。
為此,我編寫了如下所示的代碼,但它不起作用。 它顯示錯誤“ConsoleApplication1.TestClass2' 不包含帶有 1 個參數的構造函數”。
我該如何解決?
我無法在基類中創建任何方法或構造函數。 除了繼承一個類還有別的方法嗎?
我的代碼:
namespace ConsoleApplication1
{
public class TestClass1
{
public TestClass1()
{
Console.WriteLine("This is base class constructor1");
}
public TestClass1(string str1,string str2)
{
Console.WriteLine("This is base class constructor2");
}
public TestClass1(string str1,string str2,string str3)
{
Console.WriteLine("This is base class constructor3");
}
public TestClass1(string str1,string str2,string str3,string str4)
{
Console.WriteLine("This is base class constructor4");
}
}
public class TestClass2 : TestClass1
{
}
class Program
{
static void Main(string[] args)
{
TestClass2 test = new TestClass2("test");
TestClass2 test1 = new TestClass2("test,test");
}
}
}
不,您必須向派生類顯式添加構造函數。 基類的構造函數僅用於基類。 您必須鏈接您感興趣的重載的構造函數。
public class TestClass2 : TestClass1
{
public TestClass2 (string str1,string str2)
: base(str1,str2)//Call base constructor explicitly
{
}
}
上面的示例表明,我對采用兩個字符串參數的構造函數重載特別感興趣。 在這種情況下,您只能使用此重載,因為TestClass2
沒有定義任何其他構造函數。
當您定義一個構造函數時,編譯器不會為您提供默認構造函數; 因此,您可以創建 TestClass2 實例的唯一方法是new TestClass2(arg1,arg2);
嘗試這個:
public class TestClass2 : TestClass1
{
public TestClass2()
{
}
public TestClass2(string str1, string str2)
: base(str1, str2)
{
}
public TestClass2(string str1, string str2, string str3)
: base(str1, str2, str3)
{
}
public TestClass2(string str1, string str2, string str3, string str4)
: base(str1, str2, str3, str4)
{
}
}
您使用單個參數調用,即“測試”和“測試,測試”
namespace ConsoleApplication1
{
public class TestClass1
{
public TestClass1()
{
Console.WriteLine("This is base class constructor1");
}
public TestClass1(string str1, string str2)
{
Console.WriteLine("This is base class constructor2");
}
public TestClass1(string str1, string str2, string str3)
{
Console.WriteLine("This is base class constructor3");
}
public TestClass1(string str1, string str2, string str3, string str4)
{
Console.WriteLine("This is base class constructor4");
}
}
public class TestClass2 : TestClass1
{
public TestClass2(string str)
{
}
}
class Program
{
static void Main(string[] args)
{
TestClass2 test = new TestClass2("test");
TestClass2 test1 = new TestClass2("test,test");
}
}
}
public TestClass2(string str):base(str) // will invoke base class constructor
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.