为什么每次调用这个方法都会执行两次?
我有以下方法,每次调用时都会执行两次:
public static void ChangeToRepository(RepositoryTextBox textBox, int repositoryNumber)
{
MessageBox.Show("you");
int indexOfLastRepository = (textBox.RepositoryCollection.Count - 1);
if (repositoryNumber > indexOfLastRepository)
{
AddTextRepositoriesThrough(textBox, repositoryNumber, indexOfLastRepository);
}
textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText = textBox.Text;
textBox.PreviousRepositoryNumber = textBox.CurrentRepositoryNumber;
textBox.CurrentRepositoryNumber = repositoryNumber;
textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
}
该方法第一次执行时,它执行除最后一行之外的所有代码:
textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
第二次执行时,它执行所有代码。这是怎么回事?
I have the following method that is executing twice every time it is called:
public static void ChangeToRepository(RepositoryTextBox textBox, int repositoryNumber)
{
MessageBox.Show("you");
int indexOfLastRepository = (textBox.RepositoryCollection.Count - 1);
if (repositoryNumber > indexOfLastRepository)
{
AddTextRepositoriesThrough(textBox, repositoryNumber, indexOfLastRepository);
}
textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText = textBox.Text;
textBox.PreviousRepositoryNumber = textBox.CurrentRepositoryNumber;
textBox.CurrentRepositoryNumber = repositoryNumber;
textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
}
The first time that the method executes, it executes all of the code except for its last line:
textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
The second time, it executes all of the code. What's up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您分配给文本框上的
CurrentRepositoryNumber
时,它可能会触发一个事件处理程序,再次回调该函数。这似乎很可能是因为属性名称表明它控制当前存储库,然后该方法负责以某种方式显示该存储库。您可能想要临时删除、分配给该属性,然后重新登记该事件处理程序。或者也许您需要更多的重新设计来明确职责 - 通常使用 GUI 框架很难做到,最简单的选择就是使用这种模式删除、分配、重新登记:
When you assign to
CurrentRepositoryNumber
on the text box, it probably triggers an event handler that calls back to this function again. This seems likely because the property name suggests that it controls the current repository, which this method then is responsible for displaying somehow.You might want to temporary delist, assign to the property and then re-enlist that event handler. Or maybe you need more of a redesign to get the responsibilities clear - often with GUI frameworks that is hard to do, and the simplest option is to just delist, assign, re-enlist, with this kind of pattern: