在.NET 1.0的时候,大家都知道我们经常用到的是委托。有了委托呢,我们就可以像传递变量一样的传递方法。在一定程序上来讲,委托是一种强类型的托管的方法指 针,曾经也一时被我们用的那叫一个广泛呀,但是总的来说委托使用起来还是有一些繁琐。来看看使用一个委托一共要以下几个步骤:
Action dummyLambda = () => { Console.WriteLine("Hello World from a Lambda expression!"); };
// double y = square(25);
Funcdouble, double> square = x => x * x;
// double z = product(9, 5);
Funcdouble, double, double> product = (x, y) => x * y;
// printProduct(9, 5);
Actiondouble, double> printProduct = (x, y) => { Console.WriteLine(x * y); };
// var sum = dotProduct(new double[] { 1, 2, 3 }, new double[] { 4, 5, 6 });
Funcdouble[], double[], double> dotProduct = (x, y) =>
{
var dim = Math.Min(x.Length, y.Length);
var sum = 0.0;
for (var i = 0; i != dim; i++)
sum += x[i] + y[i];
return sum;
};
// var result = matrixVectorProductAsync(...);
Funcdouble, double, Taskdouble>> matrixVectorProductAsync = async (x, y) =>
{
var sum = 0.0;
/* do some stuff using await ... */
return sum;
};