在.NET 1.0的時(shí)候,大家都知道我們經(jīng)常用到的是委托。有了委托呢,我們就可以像傳遞變量一樣的傳遞方法。在一定程序上來講,委托是一種強(qiáng)類型的托管的方法指 針,曾經(jīng)也一時(shí)被我們用的那叫一個(gè)廣泛呀,但是總的來說委托使用起來還是有一些繁瑣。來看看使用一個(gè)委托一共要以下幾個(gè)步驟:
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;
};