C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari (O’Reilly).
Copyright 2016 Joseph Albahari and Ben Albahari, 978-1-491-92706-9.
在介绍了无参数基类构造函数的隐式调用之后,第 96 页陈述了以下内容:
If the base class has no accessible parameterless constructor, subclasses are forced to use the
base
keyword in their constructors.
我正在尝试创建一个代码片段来证实这一点,但尚未成功。
我的片段:
public class X
{
public int Num { get; set; }
public void Method_1()
{
Console.WriteLine("X");
}
public virtual void Method_2()
{
Console.WriteLine(Num);
}
}
public class Y : X
{
public Y()
{
Num = 1000;
}
}
private static void Main(string[] args)
{
new Y().Method_2();
}
根据书中的确认,我预计会出现编译器错误,但我什么也没得到。代码运行并正确打印 1000。
我的问题是:这本书中子类被强制使用 base 关键字 是什么意思?我正在尝试重现这种情况。
我错过了什么?
最佳答案
类 Y
确实 可以访问基类 X
的无参数构造函数,因为如果一个类没有定义构造函数,那么隐式无参数构造函数。
如果你写:
public class X
{
public X(int i){}
}
然后 Y
中将不再有 X
的可访问无参数构造函数。
关于c# - 派生类构造函数何时强制使用 base 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461524/