zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    新手学习FFmpeg
    新手学习FFmpeg
    新手学习FFmpeg
    进阶计划
    面试题汇总
    grep命令
    Quartz教程三:Job与JobDetail介绍
    spring boot热部署
    Quartz学习——SSMM(Spring+SpringMVC+Mybatis+Mysql)和Quartz集成详解(四)
    SpringBoot集成篇(二) 异步调用Async
  • 原文地址:https://www.cnblogs.com/xxxteam/p/2963334.html
Copyright © 2011-2022 走看看