C#委托三部曲Demo
因同事委托还不太会用,所以我写了一个小的委托三部曲的Demo。

调用类里的函数自动随机改变值,通过委托刷新到主界面。
这是communication类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DeledgateDemo { public class Communication { /// <summary> /// 委托三部曲 /// </summary> /// <param name="order">指令</param> /// <param name="value">值</param> public delegate void Evt_Result(string order, string value);//第一步,定义一个委托 public Evt_Result _Result;//第二步,声明一个委托 //第三步,在主界面绑定委托函数 public string Order; public int Value; public Random ra = new Random();//随机函数 string[] s1 = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; //你通讯类里的接收函数 public void OnServerReceive() { Order = s1[ra.Next(0,25)]; Value = ra.Next(-10,20); _Result(Order,Value.ToString());//委托的调用 } } }
这个是主界面的代码,因为跨线程调用控件,我这里用了 InvokeRequired
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DeledgateDemo { public partial class FrmMain : Form { public Communication communication; public FrmMain() { InitializeComponent(); communication = new Communication(); communication._Result = Show_result;//第三步,绑定委托函数 } /// <summary> /// 绑定的委托函数 /// </summary> /// <param name="order">指令</param> /// <param name="value">值</param> public void Show_result(string order,string value) { if (InvokeRequired) { Invoke(new Communication.Evt_Result(Show_result) , new object[] { order, value }); return; } else { string time = DateTime.Now.ToString("HH:mm:ss") + "_: "; if (listBox1.Items.Count > 50) { listBox1.Items.RemoveAt(listBox1.Items.Count - 1); } listBox1.Items.Insert(0, time +"指令是:"+ order+" 数值是:"+value); } } private void button1_Click(object sender, EventArgs e) { //这里通过按钮触发通讯类里的接收函数,实际运行时,自动触发接收函数。 communication.OnServerReceive(); } private void timer1_Tick(object sender, EventArgs e) { communication.OnServerReceive(); } private void button2_Click(object sender, EventArgs e) { if (button2.Text=="连续触发") { timer1.Enabled = true; timer1.Interval = 10; timer1.Start(); button2.Text = "停止"; } else { timer1.Stop(); button2.Text = "连续触发"; } } } }
非常简单的一个委托Demo。
源码连接,供初学者了解委托。
链接:https://pan.baidu.com/s/1tRRYuuzaCZGRcAiOyDSKGA
提取码:10lj

浙公网安备 33010602011771号