C# · 12月 30, 2021

c# – 如何告诉继承类不调用其基类的无参数构造函数?

我惊讶地发现,无论我在派生类中调用任何构造函数,都调用了我的基类的无参数构造函数.我认为这是什么: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); } }}解决方法 唯一的方法是明确地告诉它你想要调用哪个其他base ctor;这当然意味着你必须选择一些base ctor来调用.

你根本不能把它叫做基本的ctor – 在概念上,构建一个客户是通过首先构建一个Person,然后在它之上进行客户特定的构造.例如,假设Person有私有领域 – 如果建立客户不允许首先构建一个Person,那么如何正确地构造它们?