自强不息,止于至善

身无半文,心忧天下;手释万卷,神交古人
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# 事件机制

Posted on 2007-10-27 10:02  L.Zhang  阅读(164)  评论(0)    收藏  举报

简单的事件例子

using System;
using System.Collections.Generic;
using System.Text;

namespace EventDemo

    
//声明一个委托
    public delegate void SalaryCompute();       
    
    
//事件发布者
    public class Employee
    {
        
//定义事件
        public event SalaryCompute OnSalaryCompute;         

        
public virtual void FireEvent()       //触发事件的方法
        {
            
if (OnSalaryCompute != null)
            {   
                
//执行事件
                OnSalaryCompute();
            }
        }
    }

    
//事件的订阅者
    public class HumanResource
    {
        
//事件处理函数
        public void SalaryHandler()          
        {
            Console.WriteLine(
"Salary"); 
        }

        
public static void Main()
        {
            Employee ep 
= new Employee();
            HumanResource hr 
= new HumanResource();
            
//注册
            ep.OnSalaryCompute += new SalaryCompute(hr.SalaryHandler);      
            ep.FireEvent();        
//触发事件
            Console.Read();
        }
    }
}

带参数的事件例子

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace EventDemo
{
    
//声明一个委托
    public delegate void SalaryCompute(object sender, MyEventArgs e);

    
//定义事件参数类
    public class MyEventArgs : EventArgs
    {
        
public readonly double _salary;
        
public MyEventArgs(double salary)
        {
            
this._salary = salary;
        }
    }

    
//事件发布者
    public class Employee
    {
        
//定义事件
        public event SalaryCompute OnSalaryCompute;
        
//触发事件的方法
        public virtual void FireEvent(MyEventArgs e)
        {
            
if (OnSalaryCompute != null)
            {
                OnSalaryCompute(
this, e);
            }
        }
    }

    
//事件订阅者
    public class HumanResource
    {
        
//事件处理函数,其签名应与代理签名相同
        public void SalaryHandler(object sender, MyEventArgs e)
        {
            Console.WriteLine(
"Salary is {}", e._salary);
        }

        
public static void Main()
        {
            Employee ep 
= new Employee();
            HumanResource hr 
= new HumanResource();
            MyEventArgs e 
= new MyEventArgs(3.22);
            ep.OnSalaryCompute 
+= new SalaryCompute(hr.SalaryHandler);       //注册
            for (; ; )
            {
                Thread.Sleep(
1000);      //让程序“睡”一秒
                ep.FireEvent(e);        //触发事件
            }
        }
    }
}