c# - 关于C#中构造函数的几个问题

标签 c# .net inheritance constructor multiple-constructors

在 C# 中关于构造函数的继承:

  1. 我读到构造函数不能被继承。
  2. 如果基类包含一个构造函数,一个或多个,派生类必须总是调用其中之一?派生类总不能跳过基类的构造函数吧?
  3. 派生类可以有自己的构造函数,但它必须调用基类构造函数之一。

这些说法正确吗?

最佳答案

  1. 是的,你是对的,构造函数不是继承的。例如,仅仅因为 Object 有一个无参数构造函数,并不意味着 String 有一个无参数构造函数。来自 C# 4 规范的第 1.6.7.1 节:

    Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.

  2. 是的,派生类构造函数的构造函数链将始终通过其基类构造函数...尽管它可能是间接的,因为它可以通过 this( ...) 而不是 base(...)。如果您不指定 this(...)base(...),则等同于 base() - 调用基类中的无参数构造函数。

查看我的 article on constructor chaining获取更多信息。

关于c# - 关于C#中构造函数的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5535501/

相关文章:

java - 如何用父子对象制作对象?

c# - 如何在 C# 中启动进程,但仅在卸载所有程序集后才运行该进程?

c# - 将整数传递给 VSTO 2010 Word 插件

.net - vb 2010 中的暂停/播放按钮

python - dataclasses.asdict() 没有按预期工作

c++ - C++:返回具有继承对象的基于范围的循环迭代器

c# - 当 OnClick 代码在后台执行时禁用 Winforms 按钮

java - 如何在 Xamarin Android 中等待处理程序线程完成?

.net - 从绑定(bind)到 VM 的 CodeBehind 触发 RelayCommand

c# - 为什么要在 url 中添加 # 字符?