代码之家  ›  专栏  ›  技术社区  ›  Sunil

为什么在lambda表达式中调用委托函数时保留参数i?

  •  2
  • Sunil  · 技术社区  · 7 年前

    我有下面的C代码,我发现 i

    string[] arrayOne = {"One", "Two", "Three", "Three", "Three"};
    
    string[] newArray = arrayOne.Where ((string n, int i)=> {return i++ <=2;} ).ToArray();
    // newArray is {"One","Two", "Three"}
    

    我的期望是一个新的参数 每次调用都会传递给代理。我知道lambda表达式中使用的局部变量由于闭包而在所有调用中都被保留,但这是一个参数。

    为什么参数的值

    2 回复  |  直到 7 年前
        1
  •  3
  •   D-Shih    7 年前

    有两种替代linq where .

    public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
    public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
    

    int 类型值表示数组索引。

    public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
    

    这将返回集合中索引值小于或等于2的值。

    Where ((string n, int i)=> {return i++ <=2;})
    

    i++ 没有意义,因为您离开了委托函数作用域,auto increment i的值不会保留

        2
  •  2
  •   willeM_ Van Onsem    7 年前

    我的期望是,每次对委托的调用都会传递一个新参数。我知道lambda表达式中使用的局部变量由于闭包而在所有调用中都被保留,但这是一个参数。

    参数为 在通话之间保留。第二个参数( int i )然而,这是一个 ,就这样 根据逻辑 .Where(..) 功能本身。

    Where 它看起来或多或少像:

    public static IEnumerable<T> Where(this IEnumerable<T> data, Funct<T, int, bool> p) {
        int i = 0;
        foreach(T t in data) {
            if(p(t, i)) {
                yield return t;
            }
            i++;
        }
    }

    WhereIterator 执行逻辑的函数。我听说提供了一个更“干净”的实现来解释这个想法。

    注意 i++ :索引递增 通过 这个 在哪里? 功能。不管是怎么处理的 i 在函数中,我们每次都用另一个值调用它。安 int 参考 对象,所以你不能 数字的“状态”。

    以以下调用为例:

    csharp> arrayOne.Where ((string n, int i)=> {i += 2; return i <= 4;} )
    { "One", "Two", "Three" }
    

    具有 2 2 (或指数加2小于 4 )都是一样的。所以索引是这样的