【问题标题】:I got a " 'System.ArgumentOutOfRangeException' " when using loop?使用循环时出现“'System.ArgumentOutOfRangeException'”?
【发布时间】:2015-06-26 15:29:39
【问题描述】:
var orth = node2.Descendants("span").ToList().FindAll(x => x.GetAttributeValue("class", "").Contains("orth"));
var type_translation = node2.Descendants("span").ToList().FindAll(x => x.GetAttributeValue("class", "").Contains("cit cit-type-translation"));

if (type_translation != null)
{
    for(int i=0;i<Math.Max(type_translation.Count(),orth.Count());i++)
    {
        if(orth.Count()!=0)
        {
            results.senselist += type_translation[i].InnerText.Trim() +
                                 " " + orth[i].InnerText.Trim() +"\n";
        }
        else
        {
            results.senselist += type_translation[i].InnerText.Trim() + " ";
        }
    }
}

当调试器在orth[i].InnerText.Trim()播放时应用程序崩溃。

EX:orth.count = 5 和 type_translation.count = 7

由于我的代码:orth[6 or 7] 将为空并在orth[i] 处显示错误'System.ArgumentOutOfRangeException',type_translation 仍有数据但我不知道当它为空时如何检查它?帮我解决它:

  • 如果“a”为空,则返回“”;

(= posséder) 拥有,拥有 ⇒ Elle a 2 enfants。她有 2 个孩子。她有 2 个孩子 ⇒ Elle a une belle maison。她有一个可爱的房子。,她有一个可爱的房子。 ⇒ Il a les yeux bleus。他有蓝眼睛,他有蓝眼睛。 ⇒ Tu as de beaux cheveux。你有一头漂亮的头发,你有一头漂亮的头发。 ⇒ Il a beaucoup d'amis。他有很多朋友。他有很多朋友。

我没有足够的积分来发布照片。对不起。 https://social.msdn.microsoft.com/Forums/getfile/647259

【问题讨论】:

  • 这与 null 无关,您正在尝试访问超过其长度的列表。你可以先检查i &lt; orth.Count(),然后再检查orth[i]
  • 您应该将源 HTML 连同您想要的输出一起发布到您的问题中。我认为我们可以帮助清理代码。
  • 更新了代码。谢谢

标签: c# wpf html-agility-pack


【解决方案1】:

这个坏了:

for(int i=0;i<Math.Max(type_translation.Count(),orth.Count());i++)
{
    if(orth.Count()!=0)
    {
        results.senselist += type_translation[i].InnerText.Trim() + " " + orth[i].InnerText.Trim() +"\n";
        // ... 
    }
}

在你的脑海中运行它。当type_translation.Count &gt; orth.Countorth.Count != 0 时会发生什么?同样,orth.Count &gt; type_translation.Countorth.Count != 0 会发生什么?你有一个IndexOutOfRangeException,因为你的逻辑有缺陷。

我真的不知道你想在这里做什么,但它很乱。我的建议是弄清楚你的不变量是什么。这两个集合之间有什么关系?它们具有不同的大小是否有意义?如果是这样,是否允许任何一个大于另一个?同样,如果是这样,那么您需要确保 i 在索引之前小于它们中的任何一个的计数。

现在真是一团糟。我建议您尽早维护不变量,以便清理此逻辑。

【讨论】:

    【解决方案2】:

    你的循环条件要求两个集合的最大计数 - i&lt;Math.Max(type_translation.Count(),orth.Count()) - 所以如果一个比另一个短,那么你就会遇到问题。

    您需要使用Math.Min 或在每次访问数组之前执行检查。

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多