委托和事件的使用

 

自定义类:webcyz 包括[属性,虚方法,事件,自定义委托]

 

webcyz的派生类:重载了虚方法,截获事件触发,提前完成自定义代码.

 

其中事件参数 类:EventArgs //所有事件参数类的基类.

 

//代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 委托
{

    
class webcyz
    {
        
/// <summary>
        
/// 定义一个私有的字符串.
        
/// </summary>
        private string _text = "";
        
        
/// <summary>
        
/// 定义一个字符串属性Text.(访问属性为:public)
        
/// </summary>
        public string Text
        {
            
get { return _text; }
            
set 
            {
                _text 
= value;
                
this.OnTextChange(new EventArgs());
            }
        }

        
/// <summary>
        
/// 定义一个委托类型,用于调度字符串Text变化后方法调用的机制
        
/// </summary>
        
/// <param name="sender">调用者</param>
        
/// <param name="e">事件参数</param>
        public delegate void my_del_for_change_text(object sender, EventArgs e);


        
        
/// <summary>
        
/// 用委托声明一个事件
        
/// </summary>
        public event my_del_for_change_text Changed;

        
/// <summary>
        
/// 定义一个虚方法,用于触发事件.
        
/// </summary>
        
/// <param name="e">传递事件参数e</param>
        public virtual void OnTextChange(EventArgs e)
        {
            
if (Changed != null)
            {
                
this.Changed(this, e); 
            }
        }



    }
    
    
    
class Program
    {
        
/// <summary>
        
/// 定义webcyz的派生类.
        
/// </summary>
        class MyClass:webcyz
        {
            
/// <summary>
            
/// 重载了虚方法,从而截获事件的调用.
            
/// </summary>
            
/// <param name="e"></param>
            public override void OnTextChange(EventArgs e)
            {
                System.Windows.Forms.MessageBox.Show(
"虚函数重载");
                
base.OnTextChange(e);
            }
        }

        
static void Main(string[] args)
        {
            MyClass test 
= new MyClass();//实例化一个自定义类的子类实例.
            test.Changed += new webcyz.my_del_for_change_text(test_Changed);//给事件绑定方法.
            test.Text = "1";//改变数据.测试触发事件.
            Console.WriteLine(test.Text);//显示对象的Text属性值.
            Console.ReadKey();

        }

        
static void test_Changed(object sender, EventArgs e)
        {
            System.Windows.Forms.MessageBox.Show(
"事件的处理");
            
//throw new NotImplementedException();
        }

        

    }
}

 

 

posted @ 2011-01-21 21:16  正月龙  阅读(229)  评论(0编辑  收藏  举报
留言板