这是我的代码
public class MyClass
{
int LeftPoints;
int RightPoints;
public MyClass(int points)
: this (points, points)
{
if (points < 0)
throw new ArgumentOutOfRangeException("points must be positive");
}
public MyClass(int leftPoints, int rightPoints)
{
if (leftPoints < 0)
throw new ArgumentOutOfRangeException("leftPoints must be positive");
if (rightPoints < 0)
throw new ArgumentOutOfRangeException("rightPoints must be positive");
}
}
很明显,如果我调用new MyClass(-1)
,它会抛出消息“leftPoints 必须为正”。
可以使用 : this (points,points) 重载第一个构造函数
并且仍然获得“正确的”验证吗?
最佳答案
您无法通过从第一个构造函数调用第二个构造函数来实现这一点。
如果您追求的是代码重用,则可以采取不同的方法:
public MyClass(int points)
{
if (points < 0)
throw new ArgumentOutOfRangeException("points must be positive");
Init(points, points);
}
public MyClass(int leftPoints, int rightPoints)
{
if (leftPoints < 0)
throw new ArgumentOutOfRangeException("leftPoints must be positive");
if (rightPoints < 0)
throw new ArgumentOutOfRangeException("rightPoints must be positive");
Init(leftPoints, rightPoints);
}
private void Init(int leftPoints, int rightPoints)
{
LeftPoints = leftPoints;
RightPoints = rightPoints;
}
关于c# - 如何验证重载构造函数的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26769666/