好的,所以我想打开一个新表单,如果它还没有打开。所以我根据表格的标题或文本检查表格。现在,到目前为止它可以工作,就像在表单打开中一样,如果它已经打开,它只是把它带到前面。但我的问题是,如果它没有打开,并且我尝试创建它的新实例,它会抛出"集合已修改;枚举操作可能无法执行"。我一辈子都想不通为什么。任何帮助,不胜感激。
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
循环:
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
的基础集合。但是,如果您创建一个新表单并在那里显示它,就会发生这种情况。将另一个窗体添加到打开集合。
您可以将信息保存在 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();
...
}
<</div>
div class="one_answers"> 为什么在循环和修改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");
}