我惊讶地发现,每当我在派生类中调用 any 构造函数时,都会调用基类的无参数构造函数。我认为这就是 : base()
的用途,显式在需要时调用基本构造函数。
如何在实例化派生类时阻止调用基类构造函数?
using System;
namespace TestConstru22323
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer("Jim", "Smith");
Customer c = new Customer();
Console.WriteLine(customer.Display());
Console.ReadLine();
}
}
public class Person
{
public Person()
{
Console.WriteLine("I don't always want this constructor to be called. I want to call it explicitly.");
}
}
public class Customer : Person
{
private string _firstName;
private string _lastName;
//public Customer(string firstName, string lastName): base() //this explicitly calls base empty constructor
public Customer(string firstName, string lastName) //but this calls it anyway, why?
{
_firstName = firstName;
_lastName = lastName;
}
public string Display()
{
return String.Format("{0}, {1}", _lastName, _firstName);
}
}
}
最佳答案
唯一的方法是明确告诉它你希望它调用哪个other base ctor;这当然意味着您必须选择一些 base ctor 来调用。
您不能让它根本不调用任何基构造函数 - 概念上,构造一个 Customer
通过首先构造一个 Person
来完成, 然后做 Customer
其上的特定结构。例如,假设 Person
有private
字段 - 如果构造一个 Customer
,这些将如何正确构造被允许不首先构造一个Person
?
关于c# - 如何告诉继承类不要调用其基类的无参数构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3265958/