using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 功能:委托链的测试
/// 异常:无
/// 作者:FengWei
/// 日期:2007-06-23
/// </summary>
namespace Lesson63
{
//一、定义委托
public delegate void MethodHandler(string str);
class DelegateChain
{
//二、定义委托调用的方法
public static void MethodA(string str)
{
Console.WriteLine("MethodA-->" + str);
}
//二、定义委托调用的方法
public static void MethodB(string str)
{
Console.WriteLine("MethodB-->" + str);
}
//二、定义委托调用的方法
public static void MethodC(string str)
{
Console.WriteLine("MethodC-->" + str);
}
static void Main(string[] args)
{
//三、定义委托对象
MethodHandler call = null;
call += new MethodHandler(MethodA);
call += new MethodHandler(MethodB);
call += new MethodHandler(MethodC);
//四、委托方法被调用
call("委托方法被调用");
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 功能:委托的测试
/// 异常:无
/// 作者:FengWei
/// 日期:2007-06-23
/// </summary>
namespace Lesson63
{
//第一步:定义委托
//public delegate void MethodHandler(string name);
class DelegateTest
{
//第二步:定义运行时预调用的方法 MethodA
public static void MethodA(string name)
{
Console.WriteLine("MethodA-->" + name);
}
//第二步:定义运行时预调用的方法 MethodB
public static void MethodB(string name)
{
Console.WriteLine("MethodB-->" + name);
}
//第二步:定义运行时预调用的方法 MethodC
public static void MethodC(string name)
{
Console.WriteLine("MethodC-->" + name);
}
public static void Main()
{
//第三步:委托与方法相联系(创建delegate类型实例,传入预调用
的方法
MethodHandler callA = new MethodHandler(MethodA);
MethodHandler callB = new MethodHandler(MethodB);
MethodHandler callC = new MethodHandler(MethodC);
//第四步:委托调用方法
callA("MethodA被调用");
callB("MethodB被调用");
callC("MethodC被调用");
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 功能:多点传送(同一事件的处理采用多个方法实现)
/// 异常:无
/// 作者:FengWei
/// 日期:2007-06-23
/// </summary>
namespace Lesson63
{
//定义委托
public delegate void MyMethodHandler(int i);
public class MyEvent
{
//定义事件
public event MyMethodHandler SomeEvent;
//定义方法来触发事件
public void onSomeEvent(int i)
{
if(SomeEvent!=null)
{
//触发事件
SomeEvent(i);
}
}
}
class X
{
//被委托的方法
public void ShowX(int i)
{
Console.WriteLine("ShowX()-->" + i);
}
}
class Y
{
//被委托的方法
public void ShowY(int i)
{
Console.WriteLine("ShowY()-->" + i);
}
}
class Run
{
public static void RunShow(int i)
{
Console.WriteLine("RunShow()-->" + i);
}
public static void Main()
{
X x = new X();
Y y = new Y();
MyEvent myEvent = new MyEvent();
//多点注册
myEvent.SomeEvent+=new MyMethodHandler(RunShow);
myEvent.SomeEvent+=new MyMethodHandler(x.ShowX);
myEvent.SomeEvent += new MyMethodHandler(y.ShowY);
Console.WriteLine("注册了三个方法RunShow ShowX ShowY");
//调用触发事件的方法
myEvent.onSomeEvent(8);
//取消一个注册
myEvent.SomeEvent -= new MyMethodHandler(y.ShowY);
Console.WriteLine("注销了y.ShowY方法后");
//调用触发事件的方法
myEvent.onSomeEvent(6);
Console.ReadLine();
}
}
}