基类的构造方法未在C#中继承

时间:2018-09-07 01:43:23

标签: c# inheritance

C#中的构造函数不会被继承。必须显式调用基类的构造函数。但另一方面,也可以说基类的构造函数在子类的构造函数之前被自动调用。

有人可以解释吗?

2 个答案:

答案 0 :(得分:0)

例如,这取决于构造函数的实现方式

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

那么结果将是:

class Human {
    public Human() {
        Console.WriteLine("I am human");
    }

    public Human(int i) {
        Console.WriteLine("I am human " + i);
    }
}

class Man : Human {
    public Man() {
        Console.WriteLine("I am man");
    }

    public Man(int i) {
        Console.WriteLine("I am man " + i);
    }
}


static void Main(string[] args)
{
    Man m1 = new Man();

    Man m2 = new Man(2);

    Console.ReadLine();
}

但是如果您希望“ m2”显示为

I am human //this is m1
I am man   //this is m1
I am human //this is m2
I am man 2 //this is m2

您需要显式调用基类的结构

I am human 2 //this is m2
I am man 2   //this is m2

答案 1 :(得分:0)

一个类可以有许多构造函数。如果一个类是另一个类的子类,则每个其构造函数的每个都将调用其基类的 a 构造函数。

如果在子类构造函数中不执行任何操作,则在执行子类构造函数的代码之前,将隐式调用基类的默认(无参数)构造函数。如果您不希望这种默认行为,则可以选择要调用的构造函数。

如果我使用@Ivien的代码并将其扩展一点:

public class Human
{
    public Human()
    {
        Console.WriteLine("I am human");
    }

    public Human(int i)
    {
        Console.WriteLine("I am human " + i);
    }
}
public class Man : Human
{
    public Man()
    {
        Console.WriteLine("I am man");
    }

    public Man(int i)
    {
        // The default base class constructor will be implicitly called here
        Console.WriteLine("I am man " + i);
    }
}
public class Woman : Human
{
    public Woman()
    {
        Console.WriteLine("I am woman");
    }
    public Woman(int i) : base(i)
    {
        // I don't want the default base class constructor, so I force a call to the other constructor
        Console.WriteLine("I am woman " + i);
    }
}

您会在@Ivien的代码中看到相同的内容,但是您会看到:

I am human 2 
I am woman 2 

如果您执行以下操作:var w2 = new Woman(2);

相关问题