【问题标题】:System.ArgumentOutOfRangeException Message=Length cannot be less than zero. (Parameter 'length')System.ArgumentOutOfRangeException Message=Length 不能小于零。 (参数\'长度\')
【发布时间】:2022-10-23 04:32:54
【问题描述】:

为什么这段代码给我一个“长度不能小于零”的错误信息?

class Fraction
     {
         private double Numerator = 0;
         private double Denominator= 1;

         public static Fraction Parse(string str)
         {
             Fraction newFrac = new Fraction();

             int indexSlash = str.IndexOf("/");
             newFrac.Numerator = int.Parse(str.Substring(0, indexSlash));
             newFrac.Denominator = int.Parse(str.Substring(indexSlash + 1));

             return newFrac;
         }
     }

【问题讨论】:

  • str 中没有字符 /,所以 indexSlash 是 -1。
  • 如果str不包含/ 然后str.IndexOf("/"); 返回-1(所以indexSlash == -1)和str.Substring(0, indexSlash) 抛出异常
  • 显示您传递给 Parse() 方法的内容会有所帮助,以便确定知道,但听起来原因就是每个人都在说什么。你的分数没有/ 字符,因此它返回-1
  • 好吧,使用调试器单步执行您的代码并观察变量的值。如果你这样做,你会注意到索引斜线确实会小于零。你为什么问?好吧,查看 string.IndexOf 的官方文档,它解释了这一点......

标签: c# parsing


【解决方案1】:

string.IndexOf() 在字符串不包含预期序列时返回 -1(在这种情况下为斜杠)。所以当你用一个不包含斜杠(“/”)的字符串调用Parse()时,下一行调用str.Substring(0, -1),这显然是非法的。

【讨论】:

    【解决方案2】:

    该消息的原因是str 不包含/

    // when str doesn't contain "/", the result of IndexOf is -1
    // So indexSlash == -1 
    int indexSlash = str.IndexOf("/");
    // str.Substring(0, indexSlash)
    //   is now
    // str.Substring(0, -1)
    //   which throws the exception
    newFrac.Numerator = int.Parse(str.Substring(0, indexSlash));
    

    我建议从TryParse 开始实施:

    class Fraction {
      ...
      public static bool TryParse(string value, out Fraction result) {
        result = null;
    
        if (value is null)
          return false;
    
        int index = value.IndexOf('/');
    
        if (index <= 0)
          return false;
    
        if (!int.TryParse(str.Substring(0, index), out var num) || 
            !int.TryParse(str.Substring(index + 1), out var den))
          return false;
    
        result = new Fraction() {
          Numerator   = num, 
          Denominator = den
        };
    
        return true;
      }
    

    并基于它Parse 现在非常简单:

      public static Fraction Parse(string value) => TryParse(value, out var result)
        ? result
        : throw new FormatException("Not a valid format for fraction");
    

    【讨论】:

    • 我认为可以争论没有 / 的字符串是否按定义是非法的。指定一个没有分母的数字(等于分母 1)可能是有效的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多