这是唯一的方法,虽然我会做两个改变:
1)使用 MethodInvoker 以便您可以省略 Func 或 Action 强制转换,但继续使用递归,这样您就不会重复代码。
2)在invoke块中添加一个return,这样你就没有else块了。我宁愿添加一个额外的行而不是额外的缩进。
private void SetText(string text)
{
if (textBox1.InvokeRequired)
{
this.Invoke((MethodInvoker) delegate { SetText(text); });
return;
}
this.textBox1.Text = text;
}
再想一想,你可以有一个实用方法,它需要一个 Action 来做检查,实际的逻辑总是在 lambda 里面。
private static void InvokeIfRequired(bool required, Action action) {
// NOTE if there is an interface which contains InvokeRequired
// then use that instead of passing the bool directly.
// I just don't remember off the top of my head
if (required) {
this.Invoke((MethodInvoker) delegate { action(); });
return;
}
action();
}
private void SetText(string text)
{
InvokeIfRequired(textBox1.InvokeRequired, () => {
this.textBox1.Text = text;
});
}