c# - 为什么在调用 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
为什么在对委托的所有调用中都保留参数的值?
解决方案
有两个覆盖 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 的值不会保留
推荐阅读
- python - 使用表格视图创建附加到布局的 QScrollArea
- array-formulas - ArrayFormula 与 ADD 函数与谷歌表中的多个 IF
- class - 隐含的基类是否应该有关联?
- php - php片段在wordpress中编辑用户个人资料
- java - 在 Windows 上的 Java ProcessBuilder 中执行 MySQL 命令
- opencv - 使用opencv去除硬币阴影
- ios - 如何在 UIInputView 上设置 inputViewStyle(在 XIB 中初始化)?
- react-native - 如何在移动设备之间获得近一米的精度
- php - 帖子中的 WP 不可删除列
- python - (只能将str(不是“int”)连接到str)这是我得到的错误为什么它说我正在尝试添加字符串和int?