【问题标题】:Why does LastIndexOf give error: "Length cannot be less than zero"?为什么 LastIndexOf 给出错误:“长度不能小于零”?
【发布时间】:2017-03-23 16:55:40
【问题描述】:

这是我的代码,应该显示模式中的一些数据。目前我没有数据:

<div class="desc-plus-products align-centre ">
    @{
        var TheString = "";

        if (item.Name.Length == 0)
        {
            TheString = "Empty Name String";
        }
        else
        {
            TheString = item.Name;
        }


        var maxLength = 20;

        var trimmedString = TheString.Substring(0, Math.Min(TheString.Length, maxLength));
        trimmedString = trimmedString.Substring(0, Math.Min(trimmedString.Length, trimmedString.LastIndexOf(" ")));
    }
    <p>@trimmedString</p>
    <p>£@item.Price</p>
</div>

错误如下:

Length cannot be less than zero.
Parameter name: length

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length

Source Error: 


Line 112:
Line 113:                                var trimmedString = TheString.Substring(0, Math.Min(TheString.Length, maxLength));
Line 114:                                trimmedString = trimmedString.Substring(0, Math.Min(trimmedString.Length, trimmedString.LastIndexOf(" ")));
Line 115:                            }
Line 116:                            <p>@trimmedString</p>

Source File: D:\Websites\websitename\Views\Home\Index.cshtml    Line: 114 

我原以为if statement 会使错误消失,因为我检查字符串是否为空,如果是,我将字符串设置为临时字符串以与length 方法一起使用。

【问题讨论】:

  • 使用 string.IsNullOrWhiteSpace 而不是检查字符串长度。
  • String.LastIndexOf(string) 如果未找到子字符串,则返回 -1。
  • 如果您实际调试过代码,这将很容易发现,您是否尝试过这样做?
  • 它仍然可以回答,如果它被删除,那么什么都不会丢失。如果没有,那么至少有一个与之相关的答案。我看不出故意不回答问题的意义,即使它的质量很差。这不会改变最初提出问题的事实。
  • 无意冒犯,但您是在鼓吹在编辑该问题以改进问题后浪费时间回答一个糟糕的问题,并继续在其上发布 cmets。我想这归结为每个人都认为是浪费时间,对我来说,回答一个问题,即使是一个可怜的问题,如果它对某人有帮助不是浪费时间 - 至少对我来说。

标签: c# asp.net-mvc razor


【解决方案1】:

正如@apk 在 cmets 中提到的那样 - 您遇到的问题在第 114 行,如您的问题所示,并且与对 SubstringLastIndexOf 的调用有关。

trimmedString = trimmedString.Substring(0, Math.Min(trimmedString.Length, trimmedString.LastIndexOf(" ")));

LastIndexOf() 的调用有可能返回-1,这是产生错误的原因:

长度不能小于零。

参数名称:长度

事实上,在您发布的问题中,它说明了发生此错误的特定行号。另外,重申一下 cmets 中提到的内容,在调试器中逐步执行此操作会立即导致您发现问题所在。将来,即使在调试过程中投入一点点精力,也会比立即在此处发布错误并等待响应(可能永远不会出现)为您节省更多时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2015-07-06
    • 1970-01-01
    相关资源
    最近更新 更多