我的类中有一个默认构造函数来初始化东西。
我不想将其复制/粘贴到我拥有的另一个构造函数中,该构造函数需要在其上添加 :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/