C#界面交互Invoke的便捷写法

原始版本:

 1 private delegate void Deleagte_Void();
 2 
 3 
 4 private void NewThreadFunction()
 5 
 6 {
 7 
 8     Delegate_Void newDelegate = new Delegate_Void( this.Tasks );
 9 
10     this.Invoke( newDelegate );
11 
12 }
13 
14 
15 private void Tasks()
16 
17 {
18 
19     this.textBox.Text += "x";
20 
21 }


进化版:

1 private void NewThreadFunction()
2 
3 {
4 
5     this.Invoke(new EventHandler( delegate {  this.textBox.Text += "x"; }));
6 
7 }


继续简化版:

1 private void NewThreadFunction()
2 
3 {
4 
5     this.Invoke( new Action( () => { this.textBox.Text += "x";} ) );
6 
7 }

最终简化版:

1 private void NewThreadFunction()
2 {
3     this.Invoke( (Action)delegate{ this.textBox.Text += "X";} );
4 }

不过要注意,Action版本的delegate,只能返回void。如果要返回参数,请使用:

1 private void NewThreadFunction()
2 {
3     参数类型 result = this.Invoke((Func<参数类型>)delegate { this.textBox.Text += "X"; return new 参数类型(); });
4 }


未来版(目前不能实现):

1.当C#支持宏替换后,可实现关键字替换:

1 #DefineReplace "Invoke" this.Invoke( new Action( () => { value } ) );
2 
3 private void function NewThreadFunction()
4 {
5     #Invoke this.TextBox.Text += "x";
6 }


2.当C#支持自动Invoke后,可实现自动替换:

1 private void function NewThreadFunction()
2 {
3     this.TextBox.Text += 'x';
4 }
原文地址:https://www.cnblogs.com/xxxteam/p/2963334.html