如果您使用的是C#3,则可以使用lambda,而在C#2中,则使用匿名委托.当不需要重用行为时,这些简化了语法.我经常做的一件事是在表单代码中进行同步,而不是在控制器中进行.控制器不应该受到这种技术更具体的"管道"问题的困扰,而不是控制器逻辑.
public void ResetFields()
{
// use "delegate" instead of "() =>" if .Net version < 3.5
InvokeOnFormThread(() =>
{
firstInput.Text = Defaults.FirstInput;
secondInput.Text = Defaults.SecondInput;
thirdChoice.SelectedIndex = Defaults.ThirdChoice;
});
}
// change Action to MethodInvoker for .Net versions less than 3.5
private void InvokeOnFormThread(Action behavior)
{
if (IsHandleCreated && InvokeRequired)
{
Invoke(behavior);
}
else
{
behavior();
}
}
Run Code Online (Sandbox Code Playgroud)
作为一种做法,使表单中的所有公共方法调用"InvokeOnFormThread".或者,您可以使用AOP拦截表单上的公共方法调用并调用"InvokeOnFormThread",但上面已经运行得很好(如果您保持一致并记住总是在窗体或UserControls上的公共方法上执行).
归档时间: |
|
查看次数: |
2175 次 |
最近记录: |