一.什么是委托
C#中的委托(Delegate)类似于C或C++中函数的指针。委托(Delegate)是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。
委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。
总结:委托可以理解为一种数据类型,这种类型赋值需要赋一个与之对应的方法
delegate void MyDelegate(string s,int a);
static void Main(string[] args)
{
MyDelegate my = Mothed;
MyDelegate my1 = new MyDelegate(Mothed);
my("小明", 22);
my1("张三", 32);
Console.ReadLine();
}
static void Mothed(string s,int a)
{
Console.WriteLine(s + "的年龄" + a);
}
二.泛型委托
1.使用Action委托,可以指向无返回值的方法,参数情况如果无参则直接使用action,如果有参使用Action泛型,最多容纳16个参数
static void Method1()
{
Console.WriteLine("无返回值无参");
}
static void Main(string[] args)
{
Action a = Method1;
a();
Console.ReadLine();
}
如果说需要指向一个有参的无返回值方法
static void Method2(string s)
{
Console.WriteLine("它的名字叫"+s);
}
static void Main(string[] args)
{
Action<string> a2 = Method2;
a2("旺财");
Console.ReadLine();
}
2.Func委托
Func委托代表具有返回值类型的委托
static string Method2(string a,int b)
{
return a + "的年龄是" + b;
}
static void Main(string[] args)
{
Func<string, int, string> f2 = Method2;
Console.WriteLine(f2("小明",20));
Console.ReadLine();
}
Func委托一样最多支持16个参数的方法
三.多播委托
委托对象可使用"+“运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。”-"运算符可用于从合并的委托中移除组件委托。
使用委托的这个有用的特点,您可以创建一个委托被调用时要调用的方法的调用列表。这被称为委托的 多播(multicasting),也叫组播。
static void Main(string[] args)
{
Action<int> a = new Action<int>(Mothed);
a += Mothed1;
a += Mothed2;
a(4);
a -= Mothed1;
a(4);
Console.ReadLine();
}
static void Mothed(int i)
{
Console.WriteLine("数字1:" + i);
}
static void Mothed1(int i)
{
Console.WriteLine("数字2:" + i);
}
static void Mothed2(int i)
{
Console.WriteLine("数字3:" + i);
}