【发布时间】:2014-12-07 03:05:30
【问题描述】:
一般来说,构造函数是在类中实例化时最先执行的。
但在以下情况下,先执行类的成员方法,然后执行构造函数。
为什么会这样?
代码场景:
namespace AbsPractice
{
class Program
{
static void Main(string[] args)
{
SavingsCustomer sc = new SavingsCustomer();
CorporateCustomer cc = new CorporateCustomer();
}
}
public abstract class Customer
{
protected Customer()
{
Console.WriteLine("Constructor of Abstract Customer");
Print();
}
protected abstract void Print();
}
public class SavingsCustomer : Customer
{
public SavingsCustomer()
{
Console.WriteLine("Constructor of SavingsCustomer");
}
protected override void Print()
{
Console.WriteLine("Print() Method of SavingsCustomer");
}
}
public class CorporateCustomer : Customer
{
public CorporateCustomer()
{
Console.WriteLine("Constructor of CorporateCustomer");
}
protected override void Print()
{
Console.WriteLine("Print() Method of CorporateCustomer");
}
}
}
【问题讨论】:
-
您的控制台不会告诉您答案吗?它运行 Abstract 构造函数,然后调用 print 方法......然后它运行派生类构造函数......它几乎不能忽略你放在那里的一些代码。
标签: c# oop inheritance abstract-class