在派生类中调用基类构造函数

时间:2014-02-24 13:20:33

标签: c# .net oop inheritance constructor

基于一些要求,我想将基类的所有构造函数/方法添加到派生类中,而无需在派生类中编写方法/构造函数。为此,我编写了如下所示的代码,但它不起作用。它显示错误“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");

    }
}
}

4 个答案:

答案 0 :(得分:13)

不,您必须将构造函数显式添加到派生类中。基类的构造函数仅用于基类。你必须链接你感兴趣的重载的构造函数。

public class TestClass2 : TestClass1
{
    public TestClass2 (string str1,string str2)
    : base(str1,str2)//Call base constructor explicitly
    {

    }
}

上面的示例显示我对构造函数重载特别感兴趣,它带有两个字符串参数。在这种情况下,您只能使用此重载,因为TestClass2没有定义任何其他构造函数。

编译器在您定义一个时不会为您提供默认构造函数;因此,只有这样才能创建TestClass2的实例new TestClass2(arg1,arg2);

答案 1 :(得分:4)

试试这个:

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)
    {
    }
}

答案 2 :(得分:0)

您使用单个参数调用,即“test”和“test,test”

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");

        }
    }
}

答案 3 :(得分:-1)

 public TestClass2(string str):base(str) // will invoke base class constructor
 {
 }