using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication11 { class Program { static void Main() { User lisi = new User("lisi","123"); //订阅事件 lisi.EventLogin += new User.DelegateLogin(lisi_EventLogin); //触发事件 lisi.login(); Console.ReadKey(); } static void lisi_EventLogin() { //throw new Exception("The method or operation is not implemented."); Console.WriteLine("发现有用户登录了!!!"); } } class User //事件的发行者(事件源) { //定义委托 public delegate void DelegateLogin(); //定义事件:[类型修饰符] event [委托类型名][事件名] public event DelegateLogin EventLogin; private string name; private string password; public string Name { get { return this.name; } set { this.name = value; } } public string Password { get { return this.password; } set { this.password = value; } } public User(string name,string password) { this.name = name; this.password = password; } public void login() { Console.WriteLine("用户[{0}]正在登录中...",this.name); if (EventLogin != null)//不等于null,表示有其它事物订阅 { //引发事件 EventLogin(); } } } } 【运行结果】 用户[lisi]正在登录中... 发现有用户登录了!!!