学习委托和事件

  • 委托是对函数的封装,可以当作给方法的特征指定一个名称。而事件则是委托的一种特殊形式,当发生有意义的事情时,时间对象处理通知过程。
  • 委托是一种引用方法的类型,一旦为委托分派了方法,委托将于该方法具有完全相同的行为。
  • 下面的这个程序让我对委托有一点点了解。

程序入口

Code

 

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

namespace DelegateStudy
{
    
/// <summary>
    
/// 这个类的作用是在事件触发时传递数据用的
    
/// </summary>

    public class CatShoutEventArgs:EventArgs //eventargs是包含事件数据的类的基类
    {
        
private string _name;
        
public  string name
        
{
            
get return _name; }
            
set { _name = value; }
        }

    }

    
class Cat
    
{
        
private string name;
        
public Cat(string name)
        
{
            
this.name = name;
        }

        
//声明一个委托,这个委托有两个参数,object和catshouteventargs。
        public delegate void CatShoutEventHandler(object sender, CatShoutEventArgs args);
        
//声明事件catshout,他的事件类型是委托。
        public event CatShoutEventHandler CatShout;
        
public void Shout()
        
{
            Console.WriteLine(
"miao,我是{0}", name);
            
if (CatShout != null)
            
{
                CatShoutEventArgs e 
= new CatShoutEventArgs();
                e.name 
= this.name;
                CatShout(
this, e);
            }

        }

    }

    
class mouse
    
{
        
private string name;
        
public mouse(string name)
        
{
            
this.name = name;
        }

        
/// <summary>
        
/// 逃跑的方法中增加两个参数
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="args"></param>

        public void run(object sender,CatShoutEventArgs args)
        
{
            Console.WriteLine(
"老猫{0}来了,{1}快跑!",args.name, name);
        }


    }



}

 

posted @ 2008-01-07 22:48  乱草  阅读(365)  评论(1)    收藏  举报