如何验证重载构造函数的输入?

时间:2014-11-06 00:19:24

标签: c# constructor-overloading

这是我的代码

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)重载第一个构造函数并仍然获得“正确”的验证吗?

2 个答案:

答案 0 :(得分:2)

你无法通过调用第一个构造函数来实现这一点。

如果它是代码重用,那么你可以采取不同的方法:

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;
}

答案 1 :(得分:0)

不,没有。

您已声明new MyClass(-1)new MyClass(-1,-1)相同,后跟MyClass(int)构造函数的代码。这正是你得到的。