【问题标题】:this() and base() constructors in C#C# 中的 this() 和 base() 构造函数
【发布时间】:2011-01-31 19:13:26
【问题描述】:

似乎没有指定 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) 调用时需要“{”。这很麻烦,因为它导致我将我的代码分解为一个私有方法,而明确提供了这个功能来防止这种事情发生。

我只是做错了吗?我试过没有分隔符,分号,逗号......这似乎只是开发团队的疏忽。我很想知道为什么省略了这个,如果我以错误的方式处理这个问题,或者是否有人对替代方案有好的建议。

【问题讨论】:

标签: .net multiple-constructors


【解决方案1】:

您可以通过在链的末尾调用基本构造函数来完成此操作:

public Bar(): this(0) {}
public Bar(int schmalue): base(1) {
    // ... initialize
}

【讨论】:

  • 谢谢,这就是答案。在您陈述了类似的事情(有些更明确)之后,还有许多其他人,但这绝对是它。
【解决方案2】:

不,您只能链接到单个构造函数 - 同一类中的另一个构造函数或基构造函数。

目前还不清楚您要做什么。通常我发现在派生类中创建一个“主”构造函数是值得的:派生类中的所有其他构造函数都使用“this”来调用主构造函数,主构造函数调用“base”来调用适当的基构造函数。

虽然该模型并不适合所有场景 - 特别是当您想从不同的派生构造函数调用不同的基本构造函数时 - 它通常是一个很好的模型。 p>

【讨论】:

    【解决方案3】:

    考虑一下如果你可以在一个构造函数中同时调用thisbase 作为构造函数会发生什么。让我们假设首先会调用基本构造函数。然后,this 构造函数将被调用——它本身将调用基本构造函数。因此,基类将被实例化两次。这打破了构造函数的语义——即一个对象被构造一次。

    因此,禁止同时调用basethis。如果需要,让您委托的 this 构造函数使用特定参数调用基类。

    【讨论】:

      【解决方案4】:

      在您的设计中,我看不到 BarFoo 类之间的许多共同点。当您重新实现所有内容时,为什么Foo 派生自Bar?这两个类都有一个带有公共 getter 和私有 setter 的整数属性,并且两个类都有默认构造函数和一个允许初始化整数属性的构造函数。那么为什么这两个类仍然存在呢?

      【讨论】:

        【解决方案5】:

        Bar 中的第二个 ctor 完全是错误的。试试:

        public Bar(int schmalue)
          :base(1) //would call Foo(1)
        {
           //Gobs of initialization code
           ...
           Schmalue = schmalue;
        }
        

        第一个 ctor 中的评论似乎意味着类似

        • 使用 schmalue = 0 初始化 Bar

        • 使用 value = 1 调用 base ctor Foo

        对吗?

        为此,替换第二个 ctor 并简单地添加另一个可以处理这两个值的(私有)ctor

        public Bar(int schmalue)
          :this(1, schmalue) //would call Bar(1, schmalue)
        {
        }
        
        private Bar(int value, int schmalue)
         :base(value)
        {
            //Gobs of initialization code
           ...
           Schmalue = schmalue;
        }
        

        【讨论】:

          猜你喜欢
          • 2019-02-01
          • 2011-04-17
          • 1970-01-01
          • 1970-01-01
          • 2011-10-18
          • 1970-01-01
          • 2011-01-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多