Jas*_*tts 2 c# closures anonymous anonymous-methods c#-3.0
为什么匿名方法存在闭包?为什么不直接将状态传递给方法而不会在复制闭包变量的情况下生成新类的开销?这不仅仅是"让一切都变得全球化"的倒退吗?
有人跟我说话,我觉得我在这里错过了一些东西......
纯粹,方便......你不知道在定义时你需要多少状态,例如,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);
Run Code Online (Sandbox Code Playgroud)
在这里,我们已经将两个额外的状态传递给Predicate<T>(min和max) - 但是我们无法定义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);
Run Code Online (Sandbox Code Playgroud)
我不了解你,但我更喜欢带闭包的版本...特别是当你考虑到有多个上下文级别时它会变得多么复杂.我希望编译器担心它.
还要考虑使用这种结构的频率,特别是对于像LINQ这样的东西:你不希望以任何其他方式做到这一点......