C#委托 委托示例 事件驱动

 
   
C#委托 委托示例 事件驱动
 

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.IO;
using System.Net;

namespace ConsoleApplication2
{
     /// <summary>
     /// *************************************************************************
     /// 程序作者:李伟涛
     /// QQ:12666954
     /// 传递消息,驱动事件
     /// *************************************************************************
     /// </summary>
    
     public struct Quitperson//定义逃课人的信息
     {
         public string name;
         public string Class;
     }
     class client
     {
         public class CQuithireEventArgs:EventArgs
         {
             public readonly Quitperson quitperson;
             public CQuithireEventArgs(Quitperson quitperson)//封装事件信息
             {
                 this.quitperson=quitperson;
             }
         }
         public delegate void QuithireEventHandler(object sender, CQuithireEventArgs e);//定义委托
         public event QuithireEventHandler OnQuithire;//事件
         protected virtual void Quithire(CQuithireEventArgs e)//事件通知器
         {
             if (OnQuithire != null)
                 OnQuithire(this, e);
         }
         public void setQuitperson(Quitperson quitperson)
         {
             CQuithireEventArgs e = new CQuithireEventArgs(quitperson);
             Quithire(e);//调用通知器,通知所有登记事件的订阅着
         }
     }
     class teacher
     {
         public void report(object sender, client.CQuithireEventArgs e)
         {
             Console.WriteLine("{0}班的{1}逃课了!", e.quitperson.Class, e.quitperson.name);
         }
         public teacher(client clt)
         {
             clt.OnQuithire += new client.QuithireEventHandler(report);
         }
     }
     class schoolposident
     {
         public void Sreport(object sender, client.CQuithireEventArgs e)
         {
             Console.WriteLine("{0}:{1}班的{2}逃课了!", DateTime.Now.ToShortDateString(), e.quitperson.Class, e.quitperson.name);

         }
         public schoolposident(client clt)
         {
             clt.OnQuithire += new client.QuithireEventHandler(Sreport);
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             Quitperson q = new Quitperson();//初始化逃课人信息
             q.Class = "软件051";
             q.name = "李伟涛";
             client clt = new client();
             //订阅事件
             teacher t = new teacher(clt);
             schoolposident sp = new schoolposident(clt);
             clt.setQuitperson(q);
             Console.ReadLine();

         }
     }
   
}

posted @ 2009-05-30 13:05  小麻雀  阅读(843)  评论(0编辑  收藏  举报