是否有良好的原因倒闭不是在C#中永恒不变的? [英] Are there any good reasons why closures aren't immutable in C#?

查看:140
本文介绍了是否有良好的原因倒闭不是在C#中永恒不变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经一遍又一遍地这在我的头,我似乎无法拿出一个很好的理由,为什么C#闭包是可变的。这似乎只是一个很好的方式得到一些意想不到的后果,如果你不知道究竟发生了什么。

I've been going over and over this in my head, and I can't seem to come up with a good reason why C# closures are mutable. It just seems like a good way to get some unintended consequences if you aren't aware of exactly what's happening.

也许有人谁是一个小更懂行的可以提供一些线索?为什么C#的设计师将允许国家在一个封闭变更

Maybe someone who is a little more knowledgeable can shed some light on why the designers of C# would allow state to change in a closure?

例如:

var foo = "hello";
Action bar = () => Console.WriteLine(foo);
bar();
foo = "goodbye";
bar();

这将打印你好的第一个电话,但对于第二个电话外状态的变化,打印再见。封闭的状态进行更新,以反映更改局部变量。

This will print "hello" for the first call, but the outside state changes for the second call, printing "goodbye." The closure's state was updated to reflect the changes to the local variable.

推荐答案

C#和JavaScript,以及O'Caml和Haskell,和许多其他语言,有什么被称为词汇关闭的。这意味着内部函数可以访问局部变量的名称的在封闭的功能,而不仅仅是的的副本。与不变的符号,当然,如O'Caml或哈斯克尔语言收盘,名字等同于关闭过值,因此这两种类型的封闭之间的差异消失;但这些语言具有词法闭包就像C#和JavaScript。

C# and JavaScript, as well as O'Caml and Haskell, and many other languages, have what is known as lexical closures. This means that inner functions can access the names of local variables in the enclosing functions, not just copies of the values. In languages with immutable symbols, of course, such as O'Caml or Haskell, closing over names is identical to closing over values, so the difference between the two types of closure disappears; these languages nevertheless have lexical closures just like C# and JavaScript.

这篇关于是否有良好的原因倒闭不是在C#中永恒不变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆