我惊讶地发现我的基类的无参数构造函数在我每次调用时都会被调用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您希望它调用的基本 ctor;这当然意味着你必须选择some要调用的基本 ctor。
You can't让它根本不调用任何基础ctor -从概念上来说,构造一个Customer
首先构建一个Person
,然后做Customer
其上的特定构造。例如,假设Person
had private
字段 - 如果构建一个Customer
被允许not首先构建一个Person
?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)