为什么 LastIndexOf 给出错误: "Length cannot be less than zero" ?



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

<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:WebsiteswebsitenameViewsHomeIndex.cshtml    Line: 114 

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

正如@apk的评论中所述 - 如您的问题所示,您遇到的问题在第 114 行,并且与呼叫SubstringLastIndexOf有关。

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

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

长度不能小于零。

参数名称:长度

实际上,在您发布的问题中,它说了发生此错误的特定行号。此外,为了重申注释中提到的内容,在调试器中逐步完成此操作将立即将您带到问题所在。将来,在调试过程中投入一点点精力,也会为您节省更多的时间,而不是立即在此处发布错误并等待响应(可能永远不会到来(。

相关内容

最新更新