2

这是我的代码

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 must be positive”。

是否可以使用重载第一个构造函数: this (points, points)并仍然获得“正确”验证?

4

2 回答 2

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;
}
于 2014-11-06T00:27:41.363 回答
0

不,没有。

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

于 2014-11-06T00:23:06.580 回答