有人可以解释"获得修改封"在C#中简单来说? [英] Can someone explain "access to modified closure" in C# in simple terms?

查看:98
本文介绍了有人可以解释"获得修改封"在C#中简单来说?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
什么是'封闭'?要修改结果
访问关闭结果
访问(2)

ReSharper的抱怨下面的一段代码:

Resharper is complaining about the following piece of code:

foreach (string data in _dataList)
    DoStuff (() => field);



什么是封闭?我为什么要在乎?

What is a closure? And why should I care?

我读过有关数学和函数式编程关闭和我处于亏损就在这里。太重了,我的大脑。

I've read about closure in maths and functional programming and I'm at a loss here. Too heavy for my brain.

在简单来说,是怎么回事呢?

In simpler terms, what is going on here?

推荐答案

这里是一个相当不错的解释。

Here is a fairly good explanation.

当你从一个委托的方法体引用变量创建一个封闭。本质上,将产生一个包含到本地变量的引用的类。结果,
。如果该变量被不断地修改,当外部方法调用委托,它可能包含一个不可预测的值,甚至抛出异常。
为例,在这样一个例子:

A closure is created when you reference a variable in the body of a method from a delegate. Essentially, a class that contains a reference to the local variable is generated.
If the variable is constantly modified, when an external method calls the delegate, it may contain an unpredictable value, or even throw an exception. For example, in an example like this:

foreach (string data in _dataList)
{
    DoStuff (() => data);
}



该方法()=>数据总是将是同样的方法。如果你存储,你不知道当它最终被调用时会发生什么 - 什么会数据的价值在当时?它甚至会有效吗?如果你使用收益回报率这是特别危险的。

The method () => data is always going to be the same method. if you store it, you don't know what happens when it's eventually invoked -- what will the value of data be at the time? Will it even be valid? This is especially dangerous if you use yield return.

有一个简单的例子,没有一个迭代器,方法是:

A simpler example, without an iterator, is:

var x = 5
Func<int> f = () => x;
x = 76
f();

这篇关于有人可以解释&QUOT;获得修改封&QUOT;在C#中简单来说?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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