首页 > 解决方案 > 为什么在调用 lambda 表达式中的委托函数时保留参数 i?

问题描述

我有以下 C# 代码,我发现参数的值i被传递到 lambda 表达式委托的下一次调用。

string[] arrayOne = {"One", "Two", "Three", "Three", "Three"};

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

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

问题:

i为什么在对委托的所有调用中都保留参数的值?

标签: c#linqlambda

解决方案


有两个覆盖 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++没有意义,因为您离开了委托函数范围,自动增量 i 的值不会保留


推荐阅读