c# - 派生类构造函数何时强制使用 base 关键字?

标签 c# constructor

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/

相关文章:

c# - 如何 Type T = Type.GetType ("SomeClass");给我一个物体?

c++ - 显式复制构造函数编译错误

c# - "' BaseClass ' does not contain a constructor that takes 0 arguments."部分 C#/Protobuf 类

constructor - Findbugs 在验证构造函数参数时报告已知空值的负载

c++ - 继承构造函数不允许类似数组的初始化

java - Java 中具有隐式返回类型的构造函数

c# - Aspnet_regiis 会加密存储在外部配置文件中的连接字符串信息吗?

C# - for 循环以奇怪的间隔卡住

c# - .NET GC 停止桌面应用程序 - 性能问题

c# - 如何让页面调用usercontrol