博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

delegate和event例子

Posted on 2007-07-12 14:32  qqhe325  阅读(450)  评论(0编辑  收藏  举报
//delegate就是为了保证使用函数引用或叫函数指针时能检查函数类型
using
 System;

namespace test1
{
    
/// <summary>
    
/// Class3 的摘要说明。
    
/// </summary>
    public delegate void calleventhandler(object sender,System.EventArgs e);
    
public delegate void calleventhandler2(string s);

    
class telephone
    {
        
public telephone()
        {
            Console.WriteLine(
"客厅里有一个电话放在沙发上.");
        }

        
public event calleventhandler2 teleevent;

        
public void someonecall()
        {
            Console.WriteLine (
"叔叔打电话过来要来打麻将。。。。");
            teleevent(
"abc");
        }        
    }

    
class sound
    {
        
public sound(){}

        
public void ring(object sender,System.EventArgs e)
        {
            Console.WriteLine (
"电话铃响了.");
        }

        
public void ring2(string s)
        {
            Console.WriteLine (s
+"电话铃响了.");
        }
    }

    
class t{
    
public static void Main(){
        telephone t
=new telephone();
        sound s
=new sound();
       
        t.teleevent
+=new calleventhandler2(s.ring2);

        t.someonecall();
         }
    }

}


using System;

namespace test2
{

    
public delegate void testhandler();

    
class a{
        
public event testhandler eve;
        
public a(testhandler hand){
          eve
+=hand;
        }

        
public void run(){
           eve();
        }
    }

    
class c{
        
public static void c1(){
             Console.WriteLine (
"c1 is running");
         }

        
public static void c2()
        {
            Console.WriteLine (
"c2 is running");
        }

        
public static void c3()
        {
            Console.WriteLine (
"c3 is running");
        }
    }

    
class b{
        
public static void Main(){
            a A
=new a(new testhandler(c.c2));

            A.run();
        }
    }
}