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/archive/2013/03/16/2963334.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值