C# 执行forloop时发生IndexOutOfRangeException IEnumerable query=“不是您所期望的”; 字符串元音=“aeiou”; for(int i=0;ic!=元音[i]); foreach(查询中的字符c)控制台;

C# 执行forloop时发生IndexOutOfRangeException IEnumerable query=“不是您所期望的”; 字符串元音=“aeiou”; for(int i=0;ic!=元音[i]); foreach(查询中的字符c)控制台;,c#,.net,C#,.net,异常发生索引自动失效异常。为什么会发生这种异常一切看起来都很好 提前谢谢 解决方案 IEnumerable<char> query = "Not what you might expect"; string vowels = "aeiou"; for (int i = 0; i < vowels.Length; i++) query = query.Where (c => c != vowels[i]); foreach (char c in query) Console

异常发生索引自动失效异常。为什么会发生这种异常一切看起来都很好

提前谢谢

解决方案

IEnumerable<char> query = "Not what you might expect";
string vowels = "aeiou";
for (int i = 0; i < vowels.Length; i++)
query = query.Where (c => c != vowels[i]);
foreach (char c in query) Console.Write (c);
for(int i=0;i<元音.长度;i++)
{
char元音=元音[i];
query=query.Where(c=>c!=元音);
}

这很好,这些代码之间的区别是什么。请分享详细信息。

更改此行中变量的名称
query

query=query.Where(c=>c!=元音[i])

问题是因为

  • 人人都很懒
  • 未捕获
    i
    的值
    .Where
    查询只有在您开始打印输出时才进行实际计算,此时
    i==5
    ,导致索引越界异常


    为了更清楚地显示发生了什么,下面是循环每次迭代的等效查询(请注意,
    query
    始终指原始查询):


    查看所有查询如何为
    i
    引用相同的值?在最后一次迭代之后,
    i
    再次递增一次,这将导致循环停止。但是现在
    i==5
    ,它不再是有效的索引了

    在使用IEnumerable时,只需将.ToList()或.ToArray()添加到where子句中,就可以了

    i = 0;
    query.Where(c => c != vowels[i]);
    
    i = 1;
    query.Where(c => c != vowels[i]).Where(c => c != vowels[i]);
    
    i = 2;
    query.Where(c => c != vowels[i]).Where(c => c != vowels[i]).Where(c => c != vowels[i]);
    
    ...
    
    IEnumerable query=“不是您所期望的”;
    字符串元音=“aeiou”;
    IEnumerable result=“”;
    for(int i=0;i<元音.长度;i++)
    query=query.Where(c=>c!=元音[i])。ToList();//或者。ToArray()
    foreach(查询中的字符c)控制台;
    

    希望有帮助。

    我没有找到异常发生的原因。谢谢,我不想解决这个问题,我需要它发生的原因。
    i
    被捕获并被变异,因此当您意识到
    query
    时,它在for循环后超出范围如果编译器对此有警告,这是C#设计中的一个问题!!!每个人都会在某个时候落入陷阱。参见
    i = 0;
    query.Where(c => c != vowels[i]);
    
    i = 1;
    query.Where(c => c != vowels[i]).Where(c => c != vowels[i]);
    
    i = 2;
    query.Where(c => c != vowels[i]).Where(c => c != vowels[i]).Where(c => c != vowels[i]);
    
    ...
    
            IEnumerable<char> query = "Not what you might expect";
            string vowels = "aeiou";
            IEnumerable<char> result = "";
            for (int i = 0; i < vowels.Length; i++)
                query = query.Where(c => c != vowels[i]).ToList(); // or .ToArray()
            foreach (char c in query) Console.Write(c);