You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArgumentOutOfRangeException异常求助:Substring参数设置指导

解决ArgumentOutOfRangeException(Length不能小于0)错误

报错信息

ArgumentOutOfRangeException: Length不能小于0。参数名:length
System.String.Substring(System.Int32 startIndex, System.Int32 length)

触发错误的代码

foreach (var i in credentials)
{
    string line = i.ToString();
    if (i.ToString().Substring(0, i.ToString().IndexOf(":")).Equals(usernameInput.text) &&
        i.ToString().Substring(i.ToString().IndexOf(":") + 1).Equals(passwordInput.text))
    {   
        isExists = true;
        break;
    }
}

错误原因

当i.ToString()的结果里**没有包含冒号:**时,IndexOf(":")会返回-1。此时调用Substring(0, -1)就会触发报错——因为Substring的第二个参数(length)不能小于0。另外就算后面的Substring(-1+1)(即Substring(0))不会报错,这种没有冒号的字符串也不符合你预期的“账号:密码”格式,逻辑上也不应该进入判断。

正确写法与参数说明

修正后的代码

先提前获取冒号索引并校验合法性,同时避免重复调用ToString(),优化代码如下:

foreach (var i in credentials)
{
    string line = i.ToString();
    int colonIndex = line.IndexOf(":");
    // 先校验字符串格式是否合法(存在冒号,且冒号不在首尾)
    if (colonIndex > 0 && colonIndex < line.Length - 1)
    {
        string storedUsername = line.Substring(0, colonIndex);
        string storedPassword = line.Substring(colonIndex + 1);
        if (storedUsername.Equals(usernameInput.text) && storedPassword.Equals(passwordInput.text))
        {
            isExists = true;
            break;
        }
    }
    // 格式不合法的话直接跳过当前项
}

Substring参数规则

  • Substring(startIndex):只传起始索引时,会返回从startIndex到字符串末尾的子串,无需指定length,不会触发length相关错误。
  • Substring(startIndex, length):必须满足两个条件:length >= 0,且startIndex + length <= 字符串总长度,否则会触发参数越界异常。调用这个重载前,务必确保计算出的length是合法非负整数,且不会超出字符串范围。

内容的提问来源于stack exchange,提问作者Vinay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:35:27