本文介绍了需要帮助理解的lambda(钻营)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读加速C#我真的不明白下面的代码:

i am reading Accelerated C# i don't really understand the following code:

public static Func<TArg1, TResult> Bind2nd<TArg1, TArg2, TResult> (
    this Func<TArg1, TArg2, TResult> func,
    TArg2 constant )
{
    return (x) => func( x, constant );
}

在最后一行什么是X指的是?还有另外一个:

in the last line what is x referring to? and there's another:

public static Func<TArg2, Func<TArg1, TResult>> Bind2nd<TArg1, TArg2, TResult>
( this Func<TArg1, TArg2, TResult> func )
{
    return (y) => (x) => func( x, y );
}



我如何评价? (Y)=> (X)=> FUNC(X,Y)什么是通过其中...确实令人困惑。

How do i evaluate this? (y) => (x) => func( x, y ) what is passed where ... it does confusing.

推荐答案

让我们首先简化代码:

Func<int, int> B(Func<int, int, int> f, int c)
{
    return x=>f(x, c);
}

这仅仅是一样的:

class Locals
{
    public int c;
    public Func<int, int, int> f;
    public int Magic(int x) { return f(x, c); }
}
Func<int, int> B(Func<int, int, int> f, int c)
{
    Locals locals = new Locals();
    locals.f = f;
    locals.c = c;
    return locals.Magic;
}

现在是明确指的是什么X - x是运作魔术师的参数。

Now is it clear what x refers to? x is the parameter to function "Magic".

现在也可以使用b是这样的:

Now you can use B like this:

Func<int, int, int> adder = (a, b)=>a+b;
Func<int, int> addTen = B(adder, 10);
int thirty = addTen(20);



有意义吗?见这里发生了什么?我们正在做的两个参数的函数和固定的参数,以一个恒定的一个。因此,它成为一个参数的函数。

Make sense? See what is happening here? We're taking a function of two parameters and "fixing" one of the parameters to a constant. So it becomes a function of one parameter.

第二个示例接受了一步。再次,简化摆脱克鲁夫特,让你可以更容易地理解它:

The second example takes that one step further. Again, simplify to get rid of the cruft so that you can understand it more easily:

Func<int, Func<int, int>> B2(Func<int, int, int> f)
{
    return y=>x=>f(x,y);
}

这是一样的。

class Locals3
{
    public int y;
    public int Magic3(int x)
    {
       return x + this.y;
    }
}
class Locals2
{
    public Func<int, int, int> f;
    public Func<int, int> Magic2(int y)
    {
        Locals3 locals = new Locals3;
        locals.y = y;
        return locals.Magic3;
    }
}

Func<int, Func<int, int>> B2(Func<int, int, int> f)
{
    Locals2 locals = new Locals2();
    locals.f = f;
    return locals.Magic2;
}



所以你说

So you say

Func<int, int, int> adder = (a, b)=>a+b;
Func<int, Func<int, int>> makeFixedAdder = B2(adder);
Func<int, int> add10 = makeFixedAdder(10);
int thirty = add10(20);



B是一个参数固定器。 B2的使一个参数定影液你

然而,这B2的的的不是。 B2的一点是:

However, that's not the point of B2. The point of B2 is that:

adder(20, 10);



给出了相同的结果。

gives the same result as

B2(adder)(20)(10)

B2的原来的两个参数一个函数到一个参数每个

两个功能有意义吗?

这篇关于需要帮助理解的lambda(钻营)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:57