“System.ArgumentOutOfRangeException: Length 不能小于零”

本文关键字:小于 不能 Length System ArgumentOutOfRangeException | 更新日期: 2023-09-27 17:56:12

此代码从日志文件中读取,如果其中任何行包含 -r 和用户。句柄,它将用^替换-r,切断^之前的所有内容,切断:之后的所有内容,然后保存剩余的文本。我只是偶尔收到标题中指定的错误

if (line.Contains(user.Handle) && line.Contains("-r"))
{
    string a = line.Replace("-r", "^");
    string b = a.Substring(a.IndexOf('^') + 1);
    string c = b.Substring(0, b.IndexOf(':'));
    if (!isDuplicate(c))
    {
        listViewEx1.Items.Add(new ListViewItem(user.Handle)
        {
            SubItems = { c }
        });
        dupCheck.Add(c);
        logcount++;
    }

“System.ArgumentOutOfRangeException: Length 不能小于零”

这是使用 Substring 方法时 .NET 中经常出现的错误。人们通常认为子字符串采用开始和结束索引,这是错误的。它采用起始索引和长度。例如:

string str = "ABC123";
int length = str.Length - str.IndexOf("1") + 1;
string sub = str.Substring(0, length); // ABC1

或者更好的是,为这个可重用的部分创建一个扩展方法,以在 C# 中添加采用开始和结束索引的 Java Like 子字符串:

public static class MyExtensions
{
    public static string SubstringRange(this string str, int startIndex, int endIndex)
    {
        if (startIndex > str.Length - 1)
            throw new ArgumentOutOfRangeException(nameof(startIndex));
        if (endIndex > str.Length - 1)
            throw new ArgumentOutOfRangeException(nameof(endIndex));
        return str.Substring(startIndex, endIndex - startIndex + 1);
    }
}

用法:

string str = "ABC123";
string sub2 = str.SubstringRange(str.IndexOf("B"), str.IndexOf("2")); // BC12