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

标签 c# oop constructor

我惊讶地发现,每当我在派生类中调用 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其上的特定结构。例如,假设 Personprivate字段 - 如果构造一个 Customer,这些将如何正确构造被允许首先构造一个Person

关于c# - 如何告诉继承类不要调用其基类的无参数构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3265958/

相关文章:

c# - Silverlight 启用的 WCF 服务与 Web 服务与 ADO.NET 数据服务

c# - 在 C# Winforms 上验证文本框的输入

.net - 构造函数链和空引用测试

javascript - 如何使用文字创建包含数组的对象

java - 保留对传递给 super 构造函数的新对象的引用

c# - 将元素添加到字典中,其中键是值的属性

c# - 从 Linux 服务启动 GTK# 应用程序

javascript - “Arc 不是构造函数”错误

java - 在 Java 中从构造函数调用的静态方法

entity-framework - EF 5 模型第一部分类自定义构造函数如何?