gpt4 book ai didi

c# - C# 3.0 中匿名方法的闭包

转载 作者:行者123 更新时间:2023-11-30 19:22:33 26 4
gpt4 key购买 nike

为什么匿名方法存在闭包?为什么不直接将状态传递到方法中,而不会产生新类的开销并复制闭包变量呢?这不就是“让一切都全局化”的倒退吗?

有人贬低我,我觉得我在这里遗漏了一些东西......

最佳答案

纯粹是为了方便...例如,在定义 Predicate<T> 时,您不知道需要多少状态- 考虑:

List<int> data = new List<int> {1,2,3,4,5,6,7,8,9,10};
int min = int.Parse(Console.ReadLine()), max = int.Parse(Console.ReadLine());
List<int> filtered = data.FindAll(i => i >= min && i <= max);

这里我们将两个额外的状态位传递给 Predicate<T> ( minmax ) - 但我们无法定义 List<T>.FindAll(Predicate<T>)了解这一点,因为这是来电者的详细信息。

另一种方法是自己编写类,但这很难,即使我们很懒:

class Finder {
public int min, max;
public bool CheckItem(int i) { return i >= min && i <= max;}
}
...
Finder finder = new Finder();
finder.min = int.Parse(Console.ReadLine());
finder.max = int.Parse(Console.ReadLine());
List<int> filtered = data.FindAll(finder.CheckItem);

我不了解你,但我更喜欢带闭包的版本……尤其是当你考虑到当你有多个上下文级别时它会变得多么复杂。我希望编译器担心它。

还要考虑您使用此类构造的频率,尤其是对于 LINQ 之类的东西:您不想以任何其他方式来做...

关于c# - C# 3.0 中匿名方法的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/978553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com