标签:style blog http color io os ar 使用 sp
C#委托起源这里讲讲C#为什么用委托和什么是委托。学习过C++的都知道,C++的指针非常的灵活好用,但又给编程人员带来了很多头痛,如野指针问题等。而C#就遗弃了指针,但相应的功能通过了其他方式来实习,如C++中指针变量、引用,C#里面可以通过ref,out等实现。C++中的指针函数,C#则可以通过委托来实现,具体看如下例子。
#include <string.h>
#include <stdio.h>
int funcA(int a,int b);
int funcB(int a,int b);
int main(int argc, char *argv[])
{
int (*func)(int,int);
func = funcA;
printf("%d\n",func(10,1));
func = funcB;
printf("%d\n",func(10,1));
}
int funcA(int a,int b)
{
return a + b;
}
int funcB(int a,int b)
{
return a - b;
} 以上就是通过C++一个指针函数可以调用其他相同参数类型的多个函数。而C#中委托的功能,也可以看作是对C++这种功能的实现。具体代码如下:
<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; line-height: 21.59375px; white-space: pre-wrap;">// 节选自《</span><span style="color: rgb(0, 130, 0); font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; line-height: 21.59375px; white-space: pre-wrap;">C#入门经典》</span>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace weituo
{
class Program
{
static void Main(string[] args)
{
// 声明委托变量
ProcessDelegate process;
Console.WriteLine("请输入用逗号分隔的两个数字:");
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("输入M乘法D除法</a>");
input =Console.ReadLine();
// 初始化委托变量
if(input =="M")
process = new ProcessDelegate(Multiply);
//注释:此处也可以写process = Multiply
else
process = new ProcessDelegate(Divide);
// 使用委托调用函数
double result = process(param1,param2);
Console.WriteLine("结果:{0}",result);
Console.ReadKey();
}
// 声明委托
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;
}
}
}
标签:style blog http color io os ar 使用 sp
原文地址:http://blog.csdn.net/yzysj123/article/details/40393619