开发者

Calling overriding constructor and base in C#

开发者 https://www.devze.com 2023-03-27 03:17 出处:网络
How can I fix this error without redundant code? public Comparison2(decimal number开发者_运维技巧1, decimal number2) : base()

How can I fix this error without redundant code?

    public Comparison2(decimal number开发者_运维技巧1, decimal number2) : base()
    {
        this.Number1 = number1;
        this.Number2 = number2;
    }

    public Comparison2(decimal number1, decimal number2, int problemNumber, int subject, int seconds)
        : this(number1, number2), base(problemNumber, subject, seconds) { }


Sometimes, writing the same code multiple times is the best option, especially when it's this simple.

But if you really want to avoid repeating yourself or if your actual code is more complicated, you could just create a method to contain the code. One disadvantage to this approach is that you can't set readonly fields outside constructors.


I think your only choice is to do this:

public Comparison2(decimal number1, decimal number2) : base()
{
    this.SetNumbers(number1, number2);
}

public Comparison2(decimal number1, decimal number2, int problemNumber,
        int subject, int seconds)
    : base(problemNumber, subject, seconds)
{
    this.SetNumbers(number1, number2);
}

private void SetNumbers(decimal number1, decimal number2)
{
    this.Number1 = number1;
    this.Number2 = number2;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消