我正在写一类有理数。隐式转换会引发错误 (StackOverflowException),其原因无法理解。下面是调用代码、类和错误截图
调用隐式转换
[Test]
public void ConvertFromInt()
{
Rational r = 5;
AssertEqual(5, 1, r);
}
理性类
public class Rational
{
public int Numerator { get; set; }
public int Denominator
{
get { return Denominator; }
set
{
if (value <= 0)
IsNan = true;
else
IsNan = false;
Denominator = value;
}
}
public bool IsNan { get; set; }
public Rational(int numenator, int detominator)
{
Numerator = numenator;
Denominator = detominator;
}
public Rational(int numenator) : this(numenator,1) { }
public static implicit operator Rational(int number)
{
return new Rational(number);
}
}
在分母属性设置器中,您将值分配给同一属性。这会导致无限递归和 StackOverflowException。您应该创建一个私有字段
denominator
并为其赋值