C#托付起源
近期參加实习和奔走于各大招聘会,被问及非常多技术方面的问题。C#问的较多的就是托付和linq。
近期參加实习和奔走于各大招聘会,被问及非常多技术方面的问题。C#问的较多的就是托付和linq。
linq之前已经写过一篇文章,能够參见
http://blog.youkuaiyun.com/yzysj123/article/details/38778371。
这里讲讲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;
}
}
}