c# - 为什么不能同时使用 :base() and :this() in a C# constructor

标签 c#

我的类中有一个默认构造函数来初始化东西。

我不想将其复制/粘贴到我拥有的另一个构造函数中,该构造函数需要在其上添加 :base(otherStuff) 。我猜我将不得不这样做(或将其抽象为一种方法或类似的东西)。

但我想知道,为什么两者都不支持?

(有时当我想要一些语言不支持的东西时,这意味着我做错了什么。)

例子:

public class SomeClass : SomeBase
{
      public SomeClass()
      {
          // Init a lot of lists and stuff
      }

      public SomeClass(OtherThings otherThings): base(otherThings)
             // :this()  <----- This is not legal syntax
      {
          // Do stuff with otherThings
      }
}

最佳答案

我认为这样做的原因是基础构造函数总是在执行您类型的任何构造函数之前执行,这意味着派生自现有构造函数c1 () 您的类型已经嵌入了派生自基础构造函数 b1() - 显然您不能派生自 2 个不同的基础构造函数。

这有点令人困惑,因为 this() 构造函数实际上是从 base() 构造函数隐式派生的,因此您的代码等同于:

public class SomeClass : SomeBase
{
      public SomeClass(): **base()**
      {
          // Init a lot of lists and stuff
      }

      public SomeClass(OtherThings otherThings): base(otherThings)
             // :this()  <----- This is not legal syntax
      {
          // Do stuff with otherThings
      }
}

现在很明显你不能有 SomeClass(OtherThings otherThings): base(otherThings):this() 因为编译器将无法执行 2 个基本构造函数(base (otherThings)base())。


更新: 想到为什么禁止依赖2个构造函数我进入了这个例子:

public class SomeBase {
    public SomeBase(){}

    public SomeBase(OtherThings otherThings):this(){}
}

public class SomeClass : SomeBase
{
      public SomeClass(): base()
      {
          // Init a lot of lists and stuff
      }

      public SomeClass(OtherThings otherThings): base(otherThings)
             // :this()  <----- This is not legal syntax
      {
          // Do stuff with otherThings
      }
}

允许 SomeClass(OtherThings otherThings):base(otherThings):this() 会导致 SomeBase() 被执行两次,这是荒谬和意外的(一次:base(otherThings) 和另一次 SomeClass(): base() 都依赖于无参数构造函数 base())。

关于c# - 为什么不能同时使用 :base() and :this() in a C# constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633811/

相关文章:

c# - Linq 中的字母 GroupBy 有一个扭曲

c# - 如何更改图表 "series"中特定数据点的颜色?

c# - 不带 out 和可选参数的方法重载

c# - 在 MvvmCross 中,我如何自定义绑定(bind)属性

c# - Process.Start 是否存储远程执行文件的本地副本?

c# - Visual Studio 和条件符号

c# - 关闭表单未在应用程序 openforms 中显示

java - java "unmanaged"代码可以通过 [DllImport] 属性导入到 C# 中吗?

c# - Mini-profiler 不显示 sql 查询的任何统计信息?

c# - 仅在垂直滚动时卡住 gridview 标题