Edw*_*uay 11 c# oop constructor
我很惊讶地发现,无论何时调用派生类中的任何构造函数,都会调用我的基类的无参数构造函数.我认为这就是为什么: 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Aak*_*shM 25
唯一的方法是明确告诉它你想要它调用哪个其他基地; 这当然意味着你必须选择一些基本的ctor来打电话.
你根本不能称它为基础ctor - 概念上,构造a Customer是通过首先构造a Person,然后在Customer它之上进行特定构造来完成的.例如,假设Person有private字段 - 如果Customer允许构造a 不首先构造一个字段,它们将如何正确构造Person?
在.NET中,无论您是否调用,都将调用对象层次结构中的每个对象构造函数:base().
:base() 如果您没有显式调用它,则会隐式调用它.
:base() 如果要在父对象上调用不同的构造函数而不是默认构造函数,则可以使用它.
如果你的父构造函数中的代码每次都不应该调用,那么将代码移动到它自己的方法可能会更好,这个方法需要在构造对象后显式调用.或者,在父对象上创建一个参数化构造函数,并使用该参数来确定是否应该执行代码.
例如:
:base(true) - This executes your code.
:base(false) - This does not execute your code.
Run Code Online (Sandbox Code Playgroud)