【问题标题】:How to validate input on overloaded constructors?如何验证重载构造函数的输入?
【发布时间】:2014-11-06 00:19:24
【问题描述】:

这是我的代码

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

【问题讨论】:

  • 你可以一起编译两个异常然后抛出一个AggregateException
  • 你为什么不使用无符号整数 public MyClass(uint points) 那么它只会是积极的

标签: c# constructor-overloading


【解决方案1】:

你不能通过从第一个构造函数调用第二个构造函数来实现。

如果是代码重用,你追求的是,​​你可以采取不同的方法:

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

【讨论】:

    【解决方案2】:

    不,没有。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多