【发布时间】:2014-03-26 04:34:36
【问题描述】:
基于一些需求,我想将基类的所有构造函数/方法都添加到派生类中,而不需要在派生类中编写方法/构造函数。
为此,我编写了如下所示的代码,但它不起作用。它显示错误“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");
}
}
}
【问题讨论】:
-
你运气不好。构造函数不能在 C# 中继承。您的派生类必须声明您需要的所有构造函数。它可以使用
:base(...)语法从基类“链接”构造函数。您的问题与Why can't we use a constructor with parameter in derived classes 和可能的其他问题重复。 -
如果你有 ReSharper,你可以在派生类中点击
Alt+Ins来生成ctors。 -
我很困惑。基类是否应该具有这些构造函数?但是你写我不能在基类中创建任何方法或构造函数。你想将它们添加到派生类吗?但是你写没有在派生类中编写方法/构造函数。请澄清。
标签: c# .net oop inheritance constructor