c#的委托 ???和java代理

这算是第一个写的c#项目 写的很乱毫无章法 如果有大神刷到希望指点一二 

我的ui线程用来一直跑组态图 所以我每个操作都是重新搞个线程然后释放 因为我是和设备打交道的所有我没有考虑资源利用什么的;

1、声明一个委托

 public delegate Dictionary<string, string> Cal(SerialPort serialPort, string s, string changjia);

2、写订阅委托的方法

 public Dictionary<string, string> TriggerDelegateT(string s, string changjia)
 {
     //初始化订阅的返回值
     Dictionary<string, string> d = new Dictionary<string, string>();

     if (!this.serialPort1.IsOpen)
     {
         MessageBox.Show("请打开串口");
         return d;
     }
     if (cal != null)//如果委托不为空
     {
         //委托当前表号对应的textBox
         TextBox textBox = indexAndDeviceMap[s];
         //对应的颜色块
         Button button = allIndexDevicoMap[textBox.TabIndex];
         changeColor(button, Color.Yellow);
         int a = 3;//每个命令发三次
         while (a > 0)//定义三次
         {
             try
             {
                 //执行委托
                 d = cal.Invoke(this.serialPort1, s, changjia);
                 //委托执行成功颜色变绿
                 changeColor(button, Color.Green);
                 //logTextBox2.AppendText(",操作成功" + Environment.NewLine);
                 return d;
             }
             catch
             {
                 //委托执行失败判断是否是最后执行
                 if (a == 1)
                 {//是最后一次执行颜色变成红色
                     changeColor(button, Color.Red);
                     logger.WriteLog("表号" + s + "三次操作失败", LogUtil.LogLevel.Info);
                     // logTextBox3.AppendText(",操作失败" + Environment.NewLine);
                 }
                 else
                 {//在执行过程中颜色是黄色
                     changeColor(button, Color.Yellow);

                 }
             }
             a--;
         }
     }
     return d;

 }

3、使用委托

  public void button16_Click(object sender, EventArgs e)
  {
      Task.Run(() => {
          addDevico(sender, e);
          string changjia = this.textBox1.Text;
          cal = new Cal(DeliveryFunctionUtil.entryCali);
          for (int i = 0; i < getCheckDevicoList.Count; i++)
          {
              this.Invoke(new MethodInvoker(delegate
              {
                  logTextBox3.AppendText(DateTime.Now + " " + "表号:" + getCheckDevicoList[i] + "进入检定操作");
              }));
              TriggerDelegateT(getCheckDevicoList[i], changjia);

          }
      });

  }

5、委托的函数

最后我真的觉得c#的委托和我们java的代理好像呀,至少我看来很像哈哈哈哈哈哈哈,下面是文言一心的回答,如果大佬有不同的见解 欢迎指点我这个菜狗

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值