似乎没有指定 this() 和 base() 构造函数的语言语法。给定以下代码:
public class Bar : Foo
{
public Bar()
:base(1)
//:this(0)
{ }
public Bar(int schmalue)
:Foo(1)
{
//Gobs of initialization code
...
Schmalue = schmalue;
}
public int Schmalue { get; private set; }
}
public class Foo
{
public Foo()
{
Value = 0;
}
public class Foo(int value)
{
Value = value;
}
public int Value { get; private set; }
}
编译器给我一个错误,指出在取消注释 :this(0) 调用时需要“{”。这很麻烦,因为它导致我将我的代码分解为一个私有(private)方法,而明确提供了这个功能来防止这种事情发生。
我只是做错了吗?我尝试不使用分隔符、分号、逗号……这似乎只是开发团队的疏忽。我对为什么省略这个很感兴趣,如果我以错误的方式处理这个问题,或者是否有人对替代方案有很好的建议。
最佳答案
您可以通过在链的末尾调用基本构造函数来完成此操作:
public Bar(): this(0) {}
public Bar(int schmalue): base(1) {
// ... initialize
}
关于.net - C# 中的 this() 和 base() 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4854988/