Sunny's Technology Blog

书山有路勤为径,学海无涯苦作舟

博客园 首页 新随笔 联系 订阅 管理
引入:
事件的定义的关键字就是一个委托:EventHandler

带事件的一个类:
using System;
using System.Collections.Generic;
using System.Text;

namespace WinApp_Test.BusinessFacade
{
    
class ClassWithEvents
    
{
        
public int max;
        
public event EventHandler Finish;
        
public event EventHandler TextChange;

        
public ClassWithEvents()
        
{
            
this.max = 3;
        }


        
public void Counter()
        
{
            
while(max > 0)
            
{                
                System.Threading.Thread.Sleep(
1000);
                max 
= max - 1;
                
//RaiseEvent TextChange
                TextChange(thisnew EventArgs());
            }

            
//RaiseEvent Finish
            Finish(thisnew EventArgs());
        }

    }

}


调用:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WinApp_Test.BusinessFacade;

namespace WinApp_Test
{
    
public partial class Form1 : Form
    
{
        ClassWithEvents cls;
        EventHandler d1;
        
public Form1()
        
{
            InitializeComponent();
            
this.cls = new ClassWithEvents();
            
this.cls.Finish+=new EventHandler(cls_Finish);
            
this.cls.TextChange += new EventHandler(cls_TextChange);

            d1 
= button1_Click;
        }


        
void cls_TextChange(object sender, EventArgs e)
        
{
            
this.textBox1.Text = this.cls.max.ToString();
        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            
this.cls.max = Convert.ToInt16(this.textBox1.Text);
            
//start the action and the event will be raised later
            this.cls.Counter();
            
//this.textBox1.Text = DateTime.Now.ToString("HH:mm:ss");
        }


        
private void cls_Finish(object sender, System.EventArgs e)
        
{
            
this.textBox1.Text = "finished";
        }


        
private void button2_Click(object sender, EventArgs e)
        
{
            d1(sender, e);
        }

    }

}


有许多人问的,.Net中的委托以及事件处理。我拿简单的例子说明一下,是现实中的例子:

比如说一个公司(场景),你是老板,手下有两个员工,小张和小王。
你命令小王,如果小张玩游戏,则小王扣去小张500元钱。

这就是现实中的委托。

实际上,在写程序中,程序员就是老板,小张和小王就是两个对象。小张玩游戏是一个方法,小张还有一个游戏事件,他玩游戏激发这个事件。而小王就是事件处理对象,他负责把小张的钱扣除500。

所以,委托有如下几个要素:
1 激发事件的对象--就是小张(必须由小张自己去激发,~~~感觉有点弱智,哈哈)
2 处理对象事件的对象--就是小王
3 定义委托,就是你让小王监视小张。

如果这三个要素都满足的话,则你就写出了一个完整事件的处理。


namespace CSharpConsole
{
    
static class 场景
    
{
        [STAThread]
        
static void Main(string[] args)
        
{
            Console.WriteLine(
"场景开始了.");
            
// 生成小王
            小王 w = new 小王();
            
// 生成小账
            小张 z = new 小张();

            
// 指定监视
            z.PlayGame += new PlayGameHandler(w.扣钱);
            
            
// 开始玩游戏
            z.玩游戏();

            Console.WriteLine(
"场景结束");
            Console.ReadLine();
        }

    }




    
// 负责扣钱的人
    public class 小王
    
{
        
public 小王()
        
{
            Console.WriteLine(
"生成小王");
        }


        
public void 扣钱(object sender, EventArgs e)
        
{
            Console.WriteLine(
"小王:好小子,上班时间胆敢玩游戏");
            Console.WriteLine(
"小王:看看你小子有多少钱");
            小张 f 
= (小张)sender;
            Console.WriteLine(
"小张的钱: " + f.钱.ToString());
            Console.WriteLine(
"开始扣钱");
            
//System.Threading.Thread.Sleep(500);
            f.钱 = f.钱 - 500;
            Console.WriteLine(
"扣完了.现在小张还剩下:" + f.钱.ToString());
        }

    }


    
// 如果玩游戏,则引发事件
    public class 小张
    
{
        
// 先定义一个事件,这个事件表示“小张”在玩游戏。
        
// 这个事件需要在"小张"玩游戏的时候,由"小张"动态进行触发
        public event PlayGameHandler PlayGame;
        
        
// 保存小张钱的变量
        private int m_Money;

        
public 小张()
        
{
            Console.WriteLine(
"生成小张.");
            m_Money 
= 1000// 构造函数,初始化小张的钱。
        }


        
public int 钱 // 此属性可以操作小张的钱。
        {
            
get
            
{
                
return m_Money;
            }

            
set
            
{
                m_Money 
= value;
            }

        }


        
public void 玩游戏()
        
{
            Console.WriteLine(
"小张开始玩游戏了..");
            Console.WriteLine(
"小张:CS好玩,哈哈哈! 我玩..");
            
//System.Threading.Thread.Sleep(500);
            System.EventArgs e = new EventArgs();
            
// 触发(激活)事件,那么该事件的处理函数应该是根据
            
// z.PlayGame += new PlayGameHandler(w.扣钱); 来指定的w.扣钱
            OnPlayGame(e);
        }


        
protected virtual void OnPlayGame(EventArgs e)
        
{
            
if (PlayGame != null)
            
{
                PlayGame(
this, e);
            }

        }

    }


    
// 定义委托处理程序(定义了一个事件)
    public delegate void PlayGameHandler(object sender, System.EventArgs e);

}


另外,上面的只是一个特例,参见MSDN的讲解:http://msdn2.microsoft.com/zh-cn/library/900fyy8e(VS.80,d=ide).aspx


    用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。

为了与命名方法一起使用,委托必须用具有可接受签名的方法进行实例化。
为了与匿名方法一起使用,委托和与之关联的代码必须一起声明。

我的例子:
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WinApp_Test
{
    
// Declare delegate -- defines required signature:
    delegate string SampleDelegate(string message);

    
static class Program
    
{
        
/// <summary>
        
/// The main entry point for the application.
        
/// </summary>

        [STAThread]
        
static void Main()
        
{
            delegateTest();
        }

        
        
Equals & ReferenceEquals

        
delegate
    }


  

    
Class Point

}

输出结果是:
Hello
d1
 World
d2
例子中还有一个关于Equals和ReferenceEquals的示例
posted on 2006-03-31 21:36  Sunny  阅读(272)  评论(0)    收藏  举报