简单理解和使用 C# 委托与事件
委托和事件
委托:委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。
好的,简单了解了一下委托,接下来我们就自己来声明一个委托。
1 2 | //声明了一个 具有两个string类型参数返回值为空 的委托类型 public delegate void MyDelegate( string item1, string item2); |
接下来我们就声明一个委托对象
1 2 | //声明委托对象 public MyDelegate myDelegate; |
继续下来我们就要为这个委托对象给予实际参数
1 2 | //调用委托 myDelegate(textBox1.Text,textBox2.Text); |
下面我们来看完整的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //声明了一个 具有两个string类型参数返回值为空 的委托类型 public delegate void MyDelegate( string item1, string item2); public partial class SubWindow : Form { //定义一个委托对象 public MyDelegate myDelegate; private void btnSure_Click( object sender, EventArgs e) { //调用委托 myDelegate(textBox1.Text,textBox2.Text); } } |
然后我们再从另一个类里来实现这个委托
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //为委托赋值 并调用委托 private void button1_Click( object sender, EventArgs e) { SubWindow sw = new SubWindow(); //eg1: 将[方法]赋值给委托 【直接用方法赋值】 sw.myDelegate = AddListView; //eg2: 将[Lambda表达式]赋值给委托【Lambda表达式】 sw.myDelegate = (a, b) => { this .listView1.Items.Add(a); this .listView1.Items.Add(b); }; //eg3: 将[委托]赋值给委托 【匿名委托】 sw.myDelegate = delegate (a, b) { this .listView1.Items.Add(a); this .listView1.Items.Add(b); }; } //和委托形参列表一致的方法 public void AddListView( string item1, string item2) { this .listView1.Items.Add(item1); this .listView1.Items.Add(item2); } |
委托的用法就是这样的,现在我们来看一下事件 ,首先 声明 在委托的基础上才能声明事件
1 2 3 | //定义一个事件 public event MyEvent myEvent; //调用事件 myEvent(textBox1.Text,textBox2.Text); |
下面看事件的具体声明和使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | //注册事件 private void button1_Click( object sender, EventArgs e) { SubWindow sw = new SubWindow(); //注册事件 方式一 sw.myEvent += AddListView; //注册事件 方式二 sw.myEvent += (a, b) => { this .listView1.Items.Add(a); this .listView1.Items.Add(b); }; } //和事件形参列表一致的方法 public void AddListView( string item1, string item2) { this .listView1.Items.Add(item1); this .listView1.Items.Add(item2); } //声明了一个 具有两个string类型参数返回值为空 的委托类型 public delegate void MyDelegate( string item1, string item2); public partial class SubWindow : Form { //定义一个事件 public event MyEvent myEvent; //调用事件 private void btnSure_Click( object sender, EventArgs e) { //调用事件 myEvent(textBox1.Text, textBox2.Text); } } |
总结:事件就是委托。
本文作者:Journey&Flower
本文链接:https://www.cnblogs.com/JourneyOfFlower/p/9512810.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步