.net - C# 中的 this() 和 base() 构造函数

标签 .net multiple-constructors

似乎没有指定 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/

相关文章:

javascript:同一类型对象的不同构造函数

c# - 将连接字符串放在 applicationSettings 中有什么问题吗?

java - 以这种方式使用多个构造函数是否正确?

C++构造函数问题

.Net 2.0 - 通用列表的效率如何?

c++ - 两个成员,默认在 Base 中初始化,可能非默认在 Derived 中初始化

java - 我的 Java 三角形代码未打印完整的三角形

c# - 检测 Async/Await 的滥用 : Prevent blocking calls

c# - 适用于 .NET 的 Analytics Reporting API V4 客户端库

.net - Powershell 计算大 bigint 数字的错误值