步步为营-27-事件
1:先用委托演示
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Event_PlayMusic { //声明委托 public delegate string delPlay(); class PlayMusic { //定义委托 public delPlay del; private string name; public string Name { get { return name; } set { name = value; } } public PlayMusic(string name) { this.name = name; } public void PlaySongs() { Thread.Sleep(3000); if (del != null) { del(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Event_PlayMusic { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnPlaySong_Click(object sender, EventArgs e) { string songName = "小天狼"; //事件--先触发后响应 PlayMusic p = new PlayMusic(songName); MessageBox.Show("开始播放" + songName); p.del = () => { return "播放完毕"; }; p.PlaySongs(); MessageBox.Show(p.del()); } } }
效果
将委托改为事件
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Event_PlayMusic { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnPlaySong_Click(object sender, EventArgs e) { string songName = "小天狼"; //事件--先触发后响应 PlayMusic p = new PlayMusic(songName); MessageBox.Show("开始播放" + songName); p.del += () => { return "播放完毕"; }; string str = p.PlaySongs(); MessageBox.Show(str); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Event_PlayMusic { //声明委托 public delegate string delPlay(); class PlayMusic { //定义委托 public event delPlay del; private string name; public string Name { get { return name; } set { name = value; } } public PlayMusic(string name) { this.name = name; } public string PlaySongs() { Thread.Sleep(3000); if (del != null) { return del(); } return "事件为空!"; } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步