[英]collection was modified enumeration operation may not execute
好的,所以我想打開一個新表格,如果還沒有打開。 所以我根據表格的標題或文字檢查表格。 現在,到目前為止它的工作原理,如表格打開,如果它已經打開,它只是將它帶到前面。 但我的問題是,如果它沒有打開,我嘗試創建它的新實例,它會拋出“收集被修改;枚舉操作可能無法執行”。 而我無法為我的生活找出原因。 任何幫助表示贊賞。
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();
}
}
}
不要使用foreach
而是使用for
-loop:
for (int i = 0; i < Application.OpenForms.Count; i++ )
{
Form f = Application.OpenForms[i];
if (f.Text != ChatReader["Sender"].ToString())
{
//...
chat.Show();
chat.BringToFront();
}
// ...
}
您可以在枚舉期間更改foreach
的基礎集合。 但如果您創建一個新表單並在那里顯示它,就會發生這種情況。 您將另一個表單添加到open-collection。
您可以將信息保存在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();
...
}
為什么不在循環和修改Dictionary
時使用foraeach
? 我們可以使用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;
}
這是一篇關於它的帖子: 如何在C#中使用鍵迭代字典
真實代碼在WinForms
應用程序的MainForm
中。
/// <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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.