委托:百度百科给出的词语释义是:【释义】把事情托付给别人或别的机构(办理)
在C#中,大多时候,方法的参数是数据,但有时我们会想将 方法 作为参数,这时,我们就可以用委托。
委托一般情况下会和事件一起使用,事件说白了也是特殊的一个方法。
先看个例子吧:
有很多方法,比如求平方,求阶乘……
想让用户输入值,求该值的平方,阶乘……
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate
{
class Program
{
/// <summary>
/// 声明委托
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public delegate double TextDelegate(int i);
/// <summary>
/// 求平方
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
static double PingFang(int i)
{
return i * i;
}
/// <summary>
/// 求阶乘
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
static double JieCheng(int i)
{
if (i == 1)
return i;
else
return i * (JieCheng(--i));
}
/// <summary>
/// 主函数
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
TextDelegate td1 = new TextDelegate(PingFang);//实例化委托的一个实例td1,参数为PingFang的方法
TextDelegate td2 = new TextDelegate(JieCheng);//实例化委托的一个实例td2,参数为JieCheng的方法
Console.Write("请输入数字:");
int input = Int32.Parse(Console.ReadLine());//让用户输入一数字传给input变量
double result1 = td1(input);//使用委托
Console.WriteLine("平方返回值" + result1);
double result2 = td2(input);//使用委托
Console.WriteLine("阶乘返回值" + result2);
Console.ReadLine();
}
}
}