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

循环处理字符串数组时GetDataValue方法抛出ArgumentOutOfRangeException问题排查

解决GetDataValue循环中抛出ArgumentOutOfRangeException的问题

这个问题我之前也碰到过,核心原因是循环处理的条目里混入了不符合预期的无效数据,导致GetDataValue方法里的字符串索引操作触发了越界异常,具体拆解下:

异常根源

当GetDataValue方法里的data.IndexOf(index)找不到指定的标识(比如"Id:"、"Year:")时,会返回-1。这时候执行data.Substring(-1 + index.Length)就会因为起始索引为负数,直接抛出ArgumentOutOfRangeException。

为什么单独调用没问题但循环里出错?因为你用;分割从网站获取的字符串时,很可能出现以下情况:

  • 原字符串结尾带有;,导致分割后最后一个元素是空字符串
  • 某个条目格式损坏,缺失了某个字段的标识(比如少了"Subject:")
  • 存在空白的无效条目

这些无效条目在循环中被传入GetDataValue,就会触发异常。

解决方案

1. 先过滤无效的分割条目

在foreach循环前,先把空字符串或空白条目过滤掉,避免无效数据进入处理流程:

yearGroups = yearGroupsDataString.Split(';')
                                 .Where(s => !string.IsNullOrWhiteSpace(s))
                                 .ToArray();

2. 给GetDataValue增加安全防护

修改GetDataValue方法,先检查是否能找到目标标识,避免索引越界:

public string GetDataValue(string data, string index)
{
    // 先做基础空值检查
    if (string.IsNullOrWhiteSpace(data) || string.IsNullOrWhiteSpace(index))
        return string.Empty;

    int indexPosition = data.IndexOf(index);
    // 找不到目标标识时,返回空或自定义默认值
    if (indexPosition == -1)
        return string.Empty;

    string value = data.Substring(indexPosition + index.Length);
    if (value.Contains("|"))
    {
        value = value.Remove(value.IndexOf("|"));
    }
    return value;
}

3. 安全解析数字类型

另外,直接用Int32.Parse也存在风险,如果GetDataValue返回空或非数字字符串,会抛出格式异常。建议改用Int32.TryParse来安全转换:

foreach (string yearGroup in yearGroups)
{
    // 逐个字段安全解析,转换失败则跳过当前条目
    if (!int.TryParse(GetDataValue(yearGroup, "Id:"), out int id))
    {
        // 可以在这里加日志记录错误
        continue;
    }
    if (!int.TryParse(GetDataValue(yearGroup, "Year:"), out int year))
    {
        continue;
    }
    if (!int.TryParse(GetDataValue(yearGroup, "Subject:"), out int subject))
    {
        continue;
    }
    string groupName = GetDataValue(yearGroup, "GroupName:");

    YearGroupsData yearGroupsData = new YearGroupsData()
    {
        id = id,
        year = year,
        groupName = groupName,
        subject = subject,
    };
    SchoolData.yearGroupsDataList.Add(yearGroupsData);
}

4. 排查原始数据(可选)

如果想彻底定位问题,可以在循环里加调试输出,看看出错的条目具体是什么内容:

foreach (string yearGroup in yearGroups)
{
    // Unity用Debug.Log,其他环境用Console.WriteLine
    Debug.Log($"Processing entry: {yearGroup}");
    // 后续处理代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:17:46