【问题标题】:c# recursion - "Collection was modified; enumeration operation may not execute" [duplicate]c#recursion - “集合已修改;枚举操作可能无法执行” [重复]
【发布时间】:2012-08-24 08:44:46
【问题描述】:

我正在尝试使用递归来提升层次结构,但出现此错误:

Collection was modified; enumeration operation may not execute.

我这里的假设是,每次进入函数时,它使用的是相同的 parentRolesCopy 而不是不同的,所以当它第二次进入时,它会在原始函数调用中将 parentRolesCopy 更改为不同。

我怎样才能解决这个问题?

private IEnumerable<string> GetAllParentRoles(string role)
    {
        // GET EACH PARENT ROLE
        var parentroles = //code that gets any parents of the role passed in


        //RECURSIVELY CALL THIS FUNCTION TO KEEP GETTING PARENTS OF PARENT ROLES UNTIL NONE LEFT
        var parentRolesCopy = parentroles;
        foreach (var parentrole in parentRolesCopy)
        {
            parentroles.AddRange(GetAllParentRoles(parentrole));
        }

        return parentroles;
    }

【问题讨论】:

  • 您只是在复制参考。它们都指向同一个实际集合。

标签: c# recursion ienumerable


【解决方案1】:

您可以使副本实际上是副本,而不仅仅是指向相同的引用。一种方法是:

var parentRolesCopy = parentroles.ToArray();

【讨论】:

  • 啊,谢谢!我没有意识到我在做的只是参考原件。
【解决方案2】:

您可以使用List 或其他一些集合

var parentRolesCopy = new List<string>(parentroles);

【讨论】:

    猜你喜欢
    • 2015-06-17
    • 2011-10-05
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多