gpt4 book ai didi

c# - 在包含对象作为值的字典上使用 foreach 时出错

转载 作者:太空狗 更新时间:2023-10-30 01:23:21 24 4
gpt4 key购买 nike

我正在尝试迭代包含对象作为值的字典:

foreach (KeyValuePair<int, CMapPool_Entry> Entry in MapPool)
{
this.SendConsoleMessage(Entry.Value.Map);
}

下面可以看到CMapPool_Entry类

public class CMapPool_Entry
{
public string Map;
public string Mode;
public int Rounds;
public int Index;
public int Votes;

public bool Nominated;
public string Nominator;

public CMapPool_Entry(string map, string mode, int rounds, int index, string Nominator_LeaveEmptyStringIfNone)
{
this.Map = map;
this.Mode = mode;
this.Rounds = rounds;
this.Index = index;

// If Nominator isn't empty, set map to nominated
if (Nominator_LeaveEmptyStringIfNone != "")
{
this.Nominated = true;
this.Nominator = Nominator_LeaveEmptyStringIfNone;
}
}

public void AddVote()
{
this.Votes++;
}

public void RemoveVote()
{
if (this.Votes > 0)
this.Votes--;
}
}

这里还可以看到SendConsoleMessage方法:

    private void SendConsoleMessage(string message)
{
this.ExecuteCommand("procon.protected.pluginconsole.write", String.Format("{0}", message));
}

对我来说它看起来可行,我已经读到如何在 foreach 中编辑字典中的值会产生以下错误:“集合已修改;枚举操作可能无法执行。”

但为什么会出现此错误?我没有编辑任何值,我只是在阅读它们,对吗?如果 CObject 是 string 或 int,它工作正常,但如果它是一个对象,它就会发疯。我做错了什么,我该怎么办?


编辑:进一步调试后,我注意到 Entry.Key 可以正常使用,但只要我触摸 Entry.Value,我就会收到错误消息。由于某种原因,我随机得到了两个不同的错误:

  1. “集合已修改;枚举操作可能无法执行。”
  2. “给定的键不在字典中。”

有什么想法吗?还是以对象作为值枚举字典根本行不通?

最佳答案

正如每个人在评论中指出的那样,您在尝试阅读字典时正在另一个线程中修改字典。您在评论中写道,您通过以下方式“复制”了词典:

Dictionary<int, CMapPool_Entry> MapPool = this.Votemap_MapPool;

这不会复制字典,而是在 MapPool 中创建对 Votemap_MapPool 的引用,因此在修改代码中某处的 Votemap_MapPool 时,同时读取 MapPool 您将收到异常 System.InvalidOperationException,并显示集合已修改的消息。

要真正复制你的字典,你必须写:

Dictionary<int, CMapPool_Entry> MapPool = new Dictionary<int, CMapPool_Entry>(Votemap_MapPool);

这实际上创建了一个以 Votemap_MapPool 作为内容的 Dictionary 的新实例,当 Votemap_MapPool 被修改时,MapPool 保持不变。

关于c# - 在包含对象作为值的字典上使用 foreach 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11483232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com