C#语言中的委托和多路广播
委托delegate
有人说,C#中的委托相当于C中的函数指针。我的理解是,将函数当作变量一样来进行指向,从而实现调用。
委托是对函数原型的包装。
我是通过敲下面这两例子学会了如何进行委托的声明、实例化、调用,以及多路广播。
希望对大家有帮助:
例1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ex8_7
{
public delegate double Caculate(double x, double y); //声明委托(和需调用的函数的返回值类型、参数列表保持一致)
public class CaculateOfNumber //声明类
{
public Caculate handler; //这是一个委托型的字段
public double Add(double x, double y)
{
return x + y;
}
public double Sub(double x, double y)
{
return x - y;
}
public double Mul(double x, double y)
{
return x * y;
}
public double Div(double x, double y)
{
return (x / y) ;
}
}
class Program
{
static void Main(string[] args)
{
double a = 6, b = 4;
CaculateOfNumber cn = new CaculateOfNumber(); //创建一个对象
cn.handler = new Caculate(cn.Add); //初始化委托型字段(即委托的实例化:Caculate handler= new Caculate(cn.Add);)
//通过委托来调用方法(委托的调用格式: 委托变量名(参数列表))
Console.WriteLine("{0}与{1}的和为{2}", a, b, cn.handler(a, b));
cn.handler = cn.Sub; //委托型字段变量重新赋值
Console.WriteLine("{0}与{1}的差为{2}", a, b, cn.handler(a, b));
cn.handler = new Caculate(cn.Mul); //委托型字段变量重新赋值
//通过委托来调用方法
Console.WriteLine("{0}与{1}的积为{2}", a, b, cn.handler(a, b));
cn.handler = cn.Div;
Console.WriteLine("{0}与{1}的商为{2}", a, b, cn.handler(a, b));
//使用匿名方法来初始化委托型字段
cn.handler = delegate(double x, double y) { return (double)Math.Pow(x, y); };
Console.WriteLine("{0}的{1}次幂为{2}", a, b, cn.handler(a, b));
Console.ReadLine();
}
}
}
例2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ex8_8
{
public delegate void Caculate(double x, double y); //声明委托(委托的声明)
public class CaculateOfNumber //声明类
{
public Caculate handler; //这是一个委托型的字段
public void Add(double x, double y)
{
Console.WriteLine("{0}与{1}的和为{2}", x, y, (x + y));
}
public void Sub(double x, double y)
{
Console.WriteLine("{0}与{1}的差为{2}", x, y, (x - y));
}
public void Mul(double x, double y)
{
Console.WriteLine("{0}与{1}的积为{2}", x, y,(x * y));
}
public void Div(double x, double y)
{
Console.WriteLine("{0}与{1}的商为{2}", x, y,(x / y));
}
//public void Power(double x, double y)
//{
// Console.WriteLine("{0}的{1}次幂为{2}", x, y, Math.Pow(x, y));
//}
}
class Program
{
static void Main(string[] args)
{
double a = 6, b = 4;
CaculateOfNumber cn = new CaculateOfNumber(); //创建一个对象
//使用多路广播机制来创建委托调用列表
cn.handler = new Caculate(cn.Add); //初始化委托型字段(委托的实例化)
cn.handler += cn.Sub;
cn.handler += cn.Mul;
cn.handler += cn.Div;
//cn.handler += cn.Power;
cn.handler += delegate(double x, double y) { Console.WriteLine("{0}的{1}次幂为{2}", x, y, Math.Pow(x, y)); };
//一次性调用上面指定的所有方法(委托的调用)
cn.handler(a, b);
//重新赋值,再次调用上面指定的所有方法
a = 3; b = 3;
cn.handler(a, b);
Console.ReadLine();
}
}
}
大家可以试着敲这两串代码,运行一下,一定会比看有更深的理解。
如果我有理解错误的地方或者您有好的想法,欢迎在下方评论。
如果我的理解和提供的示例对您有帮助,可以随手点个赞
您的支持就是对我最大的鼓励