【问题标题】:Issue related to Parameterized Constructor in Base Class [duplicate]与基类中的参数化构造函数相关的问题 [重复]
【发布时间】:2015-06-15 18:23:43
【问题描述】:

我对使用继承时的构造函数有些困惑:

我有以下代码:

 class Program 
    {
        static void Main(string[] args)
        {
            ClassD obj = new ClassD(10);
            Console.ReadLine();
        }
    }
    class ClassA
    {
        public ClassA(int a)
        {
            Console.WriteLine("Constructor of ClassA");
        }
    }
    class ClassB : ClassA
    {
        public ClassB(int a)
        {
            Console.WriteLine("Parameterized Constructor of ClassB");
        }
    }
    class ClassC : ClassB
    {
        public ClassC(int a)
        {
            Console.WriteLine("Parameterized Constructor of ClassC");
        }
    }
    class ClassD : ClassC 
    {
        public ClassD(int a)
        {
            Console.WriteLine("Parameterized Constructor of ClassD");
        }
    }

当我写上面的代码时.. 编译器生成 3 错误说:

'ClassA' does not contain a constructor that takes 0 arguments  

'ClassB' does not contain a constructor that takes 0 arguments  

'ClassC' does not contain a constructor that takes 0 arguments  

那么为什么会抛出这些错误? 是否有必要在基类中有默认构造函数。

如果我不想在基类中使用默认构造函数但想在派生类中使用默认构造函数怎么办?

【问题讨论】:

标签: c# oop inheritance constructor


【解决方案1】:

那么为什么会抛出这些错误??

它不会抛出错误。编译器显示编译错误。这样做是因为基类上没有默认构造函数,而您的派生类正在使用它所需的参数调用基类。

基类中是否需要有默认构造函数。

没有。

如果我不想在基类中使用默认构造函数但想在派生类中使用默认构造函数怎么办?

那么你在派生类中提供了一个默认构造函数,但它仍然必须调用基类并提供基类构造函数所需的参数。

public ClassB() : base(0) // Or whatever value you want here for this default constructor

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2020-07-25
    • 2015-08-22
    • 1970-01-01
    相关资源
    最近更新 更多