委托的特点:1.类似于C++函数指针 2.将方法作为参数传递 3.可以用于定义回调方法
delegate是C#中的一种类型
实现一个delegate是很简单的,通过以下3个步骤即可实现一个delegate:
1. 声明一个delegate对象,它应当与你想要传递的方法具有相同的参数和返回值类型。
2. 创建delegate对象,并"将你想要传递的函数作为参数传入"。
3. 在要实现异步调用的地方,通过上一步创建的对象来调用方法。
using System;
public class MyDelegateTest
{
// 步骤1,声明delegate对象
public delegate void MyDelegate(string name);
// 这是我们欲传递的方法,它与MyDelegate具有相同的参数和返回值类型
public static void MyDelegateFunc搜索(string name)
{
Console.WriteLine("Hello, ", name);
}
public static void Main()
{
// 步骤2,创建delegate对象(实例??)
MyDelegate md = new MyDelegate(MyDelegateTest.MyDelegateFunc);
// 步骤3,调用delegate
md("sam1111");
}
}
输出结果是:Hello, sam1111
例子:将方法作为参数传递
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate {
//定义委托,它定义了可以代表的方法的类型
public delegate void GreetingDelegate(string name);
class Program {
private static void EnglishGreeting(string name) {
Console.WriteLine("Morning, " + name);
}
private static void ChineseGreeting(string name) {
Console.WriteLine("早上好, " + name);
}
//注意此方法,它接受一个GreetingDelegate类型的方法作为参数
private static void GreetPeople(string name, GreetingDelegate MakeGreeting) {
MakeGreeting(name);
}
static void Main(string[] args) {
GreetPeople("Jimmy Zhang", EnglishGreeting);
GreetPeople("张子阳", ChineseGreeting);
Console.ReadKey();
}
}
}
输出如下:
Morning, Jimmy Zhang
早上好, 张子阳
例子 :委托事件
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B(a);
C c = new C(a);
a.Raise("左");
a.Fail();
Console.ReadLine();
}
}
/// <summary>
/// 首领A举手委托
/// </summary>
/// <param name="hand"></param>
public delegate void RaiseEventHandler(string hand);
/// <summary>
/// 首领A摔杯子委托
/// </summary>
public delegate void FailEventHandler();
public class A
{
/// <summary>
/// 首领A举杯事件
/// </summary>
public event RaiseEventHandler RaiseEvent;
/// <summary>
/// 首领A摔杯子事件
/// </summary>
public event FailEventHandler FailEvent;
public void Raise(string hand)
{
Console.WriteLine("首领A{0}手举杯",hand);
//调用举杯事件,传入左手或右手作为参数
if(RaiseEvent != null)
{
RaiseEvent(hand);
}
}
public void Fail()
{
Console.WriteLine("首领A摔杯");
if(FailEvent!=null)
{
FailEvent();
}
}
}
public class B
{
A a;
public B(A a)
{
this.a = a;
a.RaiseEvent += new RaiseEventHandler(a_RaiseEvent);
a.FailEvent += new FailEventHandler(a_FaileEvent);
}
private void a_FaileEvent()
{
Attack();
}
private void a_RaiseEvent(string hand)
{
if (hand.Equals("左"))
{
Attack();
}
}
public void Attack()
{
Console.WriteLine("部下B发起进攻,大喊:猛人张飞来也!");
}
}
public class C
{
A a;
public C(A a)
{
this.a = a;
a.RaiseEvent += new RaiseEventHandler(a_RaiseEvent);
a.FailEvent += new FailEventHandler(a_FaileEvent);
}
private void a_FaileEvent()
{
Attack();
}
private void a_RaiseEvent(string hand)
{
if (hand.Equals("右"))
{
Attack();
}
}
public void Attack()
{
Console.WriteLine("部下C发起进攻,一套落英神掌打的虎虎生威!");
}
}