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 "事件为空!"; } } }