如何在没有冗余代码的情况下修复此错误?
public Comparison2(decimal number1, 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) { }
答案 0 :(得分:3)
有时候,多次编写相同的代码是最好的选择,特别是在这很简单时。
但是如果你真的想避免重复自己或者你的实际代码更复杂,你可以创建一个包含代码的方法。这种方法的一个缺点是你不能在构造函数之外设置readonly
字段。
答案 1 :(得分:2)
我认为你唯一的选择就是这样做:
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;
}