将派生类中的基本构造函数调用到第3级或第4级

时间:2016-05-09 18:01:14

标签: c# inheritance constructor

我想继承基类构造函数。

Services >>> Packages >>> ClientContract >>> Client >>> Individual                                                    >>> Business

问题在于,当你到达客户端契约类时继承构造函数时,它基本上继承了服务构造函数和包构造函数,这意味着: base()构造函数变成了一段疯狂的长代码并且只能继续越来越大。

1 个答案:

答案 0 :(得分:1)

你的问题不清楚。你在说这个吗?

Based on: .NET 4.5

C# program that uses base constructor initializer

using System;

public class A // This is the base class.
{
    public A(int value)
    {
        // Executes some code in the constructor.
        Console.WriteLine("Base constructor A()");
    }
}

public class B : A // This class derives from the previous class.
{
    public B(int value)
        : base(value)
    {
        // The base constructor is called first.
        // ... Then this code is executed.
        Console.WriteLine("Derived constructor B()");
    }
}

可以找到该示例here

所以在你的情况下,它将是

public class Services
{
    public Services()
    {
        Console.WriteLine("Base Constructor Services()");
    }
}

public class Packages : Services
{
    public Packages()
        : base()
    {
        Console.WriteLine("Derived constructor Packages()");
    }
}

public class ClientContract : Services
{
    public ClientContract()
        : base()
    {
        Console.WriteLine("Derived constructor ClientContract()");
    }
}

public class Client: Services
{
    public Client()
        : base()
    {
        Console.WriteLine("Derived constructor Client()");
    }
}
public class Individual : Services
{
    public Individual()
        : base()
    {
        Console.WriteLine("Derived constructor Individual()");
    }
}