C# 集合被修改枚举操作可能无法执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19083507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
collection was modified enumeration operation may not execute
提问by Dr Archer
Okay, so I want to open a new form if it isn't already open. So I check for the form based on the Title or text of the form. Now, so far it works, as in the form opens and if it is already open, it just brings it to the front. But my problem being, that if it isn't open, and I try to create a new instance of it, it throws me the "Collection was modified; Enumeration operation may not execute". And I cannot for the life of me figure out why. Any help is appreciated.
好的,所以我想打开一个尚未打开的新表单。所以我根据表单的标题或文本检查表单。现在,到目前为止它可以工作,因为在表单中打开,如果它已经打开,它只是将它带到前面。但我的问题是,如果它没有打开,并且我尝试创建它的新实例,它会向我抛出“集合已修改;枚举操作可能无法执行”。我一生都无法弄清楚原因。任何帮助表示赞赏。
foreach (DataRow iRow in chatcheck.Rows)
{
FormCollection fc = Application.OpenForms;
foreach (Form f in fc)
{
if (f.Text != ChatReader["Sender"].ToString())
{
ChatBox chat = new ChatBox();
Connection.ConnectionStrings.chatopen = ChatReader["Sender"].ToString();
chat.Text = Connection.ConnectionStrings.chatopen;
chat.Show();
chat.BringToFront();
}
else if (f.Text == ChatReader["Sender"].ToString())
{
f.BringToFront();
}
}
}
采纳答案by Valery Petrov
You can save the information in a foreach loop (e.g. in a List<>), and then open the form, using this information.
您可以将信息保存在 foreach 循环中(例如在 List<> 中),然后使用此信息打开表单。
var myList = new List<something>();
foreach (DataRow iRow in chatcheck.Rows)
{
FormCollection fc = Application.OpenForms;
foreach (Form f in fc)
{
if (f.Text != ChatReader["Sender"].ToString())
{
myList.Add(...)
}
else if (f.Text == ChatReader["Sender"].ToString())
{
f.BringToFront();
}
}
}
?
?
foreach (var val in myList)
{
ChatBox chat = new ChatBox();
...
}
回答by Tim Schmelter
Don't use a foreach
but a for
-loop:
不要使用foreach
但一个 -for
循环:
for (int i = 0; i < Application.OpenForms.Count; i++ )
{
Form f = Application.OpenForms[i];
if (f.Text != ChatReader["Sender"].ToString())
{
//...
chat.Show();
chat.BringToFront();
}
// ...
}
You canot change the underlying collection of a foreach
during enumeration. But that happens if you create a new form and show it there. You add another form to the open-collection.
您不能foreach
在枚举期间更改 a 的基础集合。但是如果您创建一个新表单并将其显示在那里,就会发生这种情况。您将另一个表单添加到开放集合中。
回答by open and free
Why not to use a foraeach
when looping through and modifying a Dictionary
??
We can loop through a dictionary using foreach
with its keys as below:
为什么foraeach
在循环和修改 a 时不使用a Dictionary
?? 我们可以使用foreach
它的键循环遍历字典,如下所示:
//get key collection from dictionary into a list to loop through
List<int> keys = new List<int>(Dictionary.Keys);
// iterating key collection using simple for-each loop
foreach (int key in keys)
{
// Now we can perform any modification with values of dictionary.
Dictionary[key] = Dictionary[key] - 1;
}
Here is a Post about it : How To Iterate a Dictionary Using Keys In C#
这是一篇关于它的帖子:如何在 C# 中使用键迭代字典
回答by Developer
Real life code is inside of the MainForm
of WinForms
app.
现实生活中的代码是内部MainForm
的WinForms
应用程序。
/// <summary>
/// Creates and connects the hub connection and hub proxy.
/// </summary>
private async void ConnectWithRetryAsync()
{
Connection = new HubConnection(Properties.Settings.Default.ServerBaseUrl);
Connection.Closed += Connection_Closed;
Connection.Error += Connection_Error;
HubProxy = Connection.CreateHubProxy("signalcalendar");
//Handle incoming event from server: use Invoke to write to log from SignalR's thread
HubProxy.On<CalendarUpdateRequest>("UpdateCalendarEvent", (calendarUpdateRequest) =>
this.Invoke((Action)(() =>
{
try
{
if (calendarUpdateRequest == null) return;
// Reject my own calendar's changes
if (calendarUpdateRequest.UserInfo.UserId == Program.UserInfo.UserId) return;
//Notify all opened Form about Calendar changes
for (int i = 0; i < Application.OpenForms.Count; i++)
{
var openForm = Application.OpenForms[i];
try
{
var currentFormType = openForm.GetType();
if (currentFormType == typeof(CommonForm))
{
if ((openForm as CommonForm).AppWindowType == AppWindowTypes.FactTruckForm ||
(openForm as CommonForm).AppWindowType == AppWindowTypes.PlanTruckForm ||
(openForm as CommonForm).AppWindowType == AppWindowTypes.FactExcForm ||
(openForm as CommonForm).AppWindowType == AppWindowTypes.PlanExcForm)
{
(openForm as CommonForm).CalendarHasBeenChanged(calendarUpdateRequest);
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
))
);
#region Connect to the Server
try
{
await Connection.Start();
}
catch (HttpRequestException ex)
{
var errorMessage = "There is no connection with Server. Check your netwrok and Server App state";
logger.Error(errorMessage);
logger.Error(ex);
MetroMessageBox.Show(this, errorMessage, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
}
#endregion
//Activate UI
logger.Info("COnnection has been established OK");
}