【问题标题】:Incorrect data in Constructor构造函数中的数据不正确
【发布时间】:2010-09-04 14:13:48
【问题描述】:

我有课

class Rational
{
   private int _n;
   private int _m;

   public Rational(int n, int m)
   {
      _n = n;
      _m = m;
   }
}

但是m 应该是> 0。我应该怎么做才能通知用户他向构造函数输入了错误的数据?

【问题讨论】:

    标签: c# error-handling constructor


    【解决方案1】:

    您可以抛出ArgumentException 或添加需要m > 0 的合约

    if(m <= 0) throw new ArgumentException("Denominator must be positive");
    

    public Rational(int n, int m)
    {
        Contract.Requires(m > 0);
        _n = n;
        _m = m;
    }
    

    【讨论】:

    • @Sergey Gavruk 在构造函数中抛出ArgumentExceptionArgumentNullException 是完全正常的,并且在许多核心.net 类中都使用了这种做法。
    • @Sergey - 我知道,只要没有资源(例如文件句柄)泄露,就没有理由不这样做。 BCL 类这样做很常见 - 如果无法在有效状态下创建对象,那么它可以做的唯一明智的事情就是抛出异常。
    【解决方案2】:

    虽然它是有争议的(尤其是在 C++ 中),但我认为这里最直接的做法是抛出 ArgumentException

    Microsoft 指南 recommend throwing exceptions from constructors 在有意义的情况下,例如,如果参数不允许创建可用对象(这是您的情况)。

    【讨论】:

      【解决方案3】:

      在 C# 中,http://msdn.microsoft.com/en-us/library/ms229060.aspx 文章中有官方构造函数设计指南,其中说Do throw exception from instance constructors if appropriate

      我会说像其他人所说的那样抛出一个参数异常,但我会使用一些警告,如果您在对象中创建了任何可处置的东西,请在抛出异常之前进行清理

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-08
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 2016-11-04
        • 2013-01-27
        • 2019-02-27
        • 1970-01-01
        相关资源
        最近更新 更多