using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EventTest
{
//继承.EventArgs事件处理类,MouseEventArgs鼠标事件处理类.
public class MyEventArgs : EventArgs
{
public string str;
}
//声明委托的对象,其中第一个参数表示事件的触发对象,第二个参数表示处理事件的对象.
public delegate void MyEventHandler1( object sender , MyEventArgs e);
class Class1
{
//创建委托对象并包含事件处理函数
3 public Class1(Class2 class2)
{
//创建委托,包含事件处理函数
4 MyEventHandler1 mh1 = new MyEventHandler1(Method1);
//订阅事件,事件Event1由委托mh1处理
5 class2.Event1 += mh1;
}
//事件处理函数
public void Method1(object sender,MyEventArgs e)
{
12 Console.WriteLine("事件处理的结果: " + e.str);
}
}
//通过委托来调用被包含的方法
class Class2
{
//定义事件
public event MyEventHandler1 Event1;
//触发事件
public void mEvent1(MyEventArgs e)
{
9 if (Event1 != null)
{
10 Event1(this, e);
13
}
}
}
class Program
{
static void Main(string[] args)
{
1 Class2 class2 = new Class2();
2 Class1 class1 = new Class1(class2);
6 MyEventArgs e1 = new MyEventArgs();
7 e1.str = "Hello";
8 class2.mEvent1(e1);
14 Console.ReadKey();
}
}
}
委托使用流程:声明委托对象--->定义需要被调用的方法--->将方法包含在委托中--->通过委托调用方法.