委托用于将方法作为参数传递给其他方法.
与委托的签名(由返回类型和参数组成)匹配的任何可访问类或结构中的任何方法都可以分配给该委托。
定义委托:
delegate void SayDelegate(string name);
public delegate void Del(string message);
delegate double ProcessDelegate(double param1,double param2); 实例一:(来自<.NET深入体验与实战精要>)
Code
using System;
using System.Collections.Generic;
using System.Text;
namespace DelegateTest
{
public delegate void SayDelegate(string name);
public class ClassPeople
{
public void SayChinese(string name)
{
Console.WriteLine("你好," + name);
}
public void SayEnglish(string name)
{
Console.WriteLine("Hello," + name);
}
//注意此方法,它接受一个SayDelegate类型的方法作为参数
public void DoWork(string name, SayDelegate MakeSay)
{
MakeSay(name);
}
}
class Program
{
static void Main(string[] args)
{
ClassPeople cp = new ClassPeople();
cp.DoWork("牛牛", cp.SayChinese);
cp.DoWork("NiuNiu", cp.SayEnglish);
Console.ReadLine();
}
}
}
//DoWork接收一个参数变量 MakeSay, 它可以代表一个方法.
//参数变量MakeSay被赋值为 SayChinese或者SayEnglish. 也可以这样使用委托:
Code
class Program
{
static void Main(string[] args)
{
ClassPeople cp = new ClassPeople();
string name1 = "牛牛";
string name2 = "NiuNiu";
SayDelegate delegate1 = cp.SayChinese;
SayDelegate delegate2 = cp.SayEnglish;
cp.DoWork(name1, delegate1);
cp.DoWork(name2, delegate2);
//cp.DoWork("牛牛", cp.SayChinese);
//cp.DoWork("NiuNiu", cp.SayEnglish);
Console.ReadLine();
}
} 委托SayDelegate和类型string地位一样,都是定义了一种参数类型.
实例二:(来自<c#入门经典>)
Code
using System;
using System.Collections.Generic;
using System.Text;
namespace DelegateTest
{
class Program
{
delegate double ProcessDelegate(double param1,double param2); //定义一个委托
static double Multiply(double param1, double param2)
{
return param1 * param2;
}
static double Divide(double param1, double param2)
{
return param1 / param2;
}
static void Main(string[] args)
{
ProcessDelegate process; //使用委托声明一个变量
Console.WriteLine("Enter 2 numbers separated with a comma:");
string input = Console.ReadLine();
int commaPos = input.IndexOf(',');
double param1=Convert.ToDouble(input.Substring(0,commaPos));
double param2=Convert.ToDouble(input.Substring(commaPos+1,input.Length-commaPos-1)); //使用逗号分开两个数字
Console.WriteLine("Enter M to Multiply or D to Divide:");
input=Console.ReadLine();
if(input=="M")
process=new ProcessDelegate(Multiply); //初始化process委托变量
else
process=new ProcessDelegate(Divide);
Console.WriteLine("Result:{0}",process(param1,param2));//使用委托调用所选的函数
Console.ReadKey();
}
}
}