简单适用的 .NET 事件实例代码

来源:互联网 发布:jquery 数组排序 编辑:程序博客网 时间:2024/05/21 19:29
using System;

namespace ConsoleApplication1
{
    
public delegate void MyDelegate();
    
public interface IEvent
    {
        
event MyDelegate MyEvent;
        
void FireAway();
    }
    
public class MyEventClass:IEvent
    {
        
public event MyDelegate MyEvent;
        
public void FireAway()
        {
            
if(MyEvent!=null)
                MyEvent();
            
else
                Console.WriteLine(
"MyEvent failed!  ");
        }
    }
    
public class MainClass
    {
        
static private void eventTest_A()
        {
            Console.WriteLine(
"call:  eventTest_A ");
            
return;
        } 
        
static private void eventTest_B()
        {
            Console.WriteLine(
"call:  eventTest_B ");
            Console.ReadLine();
            
return;
        }
        
static public void Main()
        {
            
/*
             * 可以使用接口定义!
            IEvent iMy;
            iMy=new MyEventClass();
            iMy.FireAway();
            iMy.MyEvent +=new MyDelegate(f);
            iMy.MyEvent +=new MyDelegate(fl);
            iMy.FireAway();
            
*/

            MyEventClass myEvent
=new MyEventClass();
            myEvent.FireAway();
            myEvent.MyEvent 
+=new MyDelegate(eventTest_A);
            myEvent.MyEvent 
+=new MyDelegate(eventTest_B);
            myEvent.FireAway();
        
        }
    }
}