基於某些要求,我想將基類的所有構造函數/方法添加到派生類中,而無需在派生類中編寫方法/構造函數。爲此我編寫了如下所示的代碼,但它不起作用。它顯示錯誤「ConsoleApplication1.TestClass2」不包含帶1個參數的構造函數「。我怎麼才能得到它?我不能在基類中創建任何方法或構造函數。除了繼承一個類之外,還有其他方法嗎? Belos是我的代碼在派生類中調用基類構造函數
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");
}
}
}
你有沒有運氣調用。構造函數不能在C#中繼承。你的派生類將不得不聲明你需要的所有構造函數。它可以用':base(...)'語法「鏈接」基類的構造函數。你的問題是[爲什麼我們不能在派生類中使用參數的構造函數](http://stackoverflow.com/questions/12167234/)以及其他可能的副本。 –
如果您有ReSharper,您可以在派生類中點擊'Alt + Ins'來生成ctors。 –
我很困惑。基類應該有這些構造函數嗎?但是你寫了_I不能在基類中創建任何方法或構造函數._你想將它們添加到派生類嗎?但是你在派生類中編寫_而沒有編寫方法/構造函數._請澄清。 –