我刚刚遇到了最意想不到的行为.我确信这有一个很好的理由.有人可以帮忙解释一下吗?
考虑以下代码:
var nums = new int[] { 1, 2, 3, 4 };
var actions = new List<Func<int>>();
foreach (var num in nums)
{
actions.Add(() => num);
}
foreach (var num in nums)
{
var x = num;
actions.Add(() => x);
}
foreach (var action in actions)
{
Debug.Write(action() + " ");
}
Run Code Online (Sandbox Code Playgroud)
输出对我来说有点意外:
4 4 4 4 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
显然,lambda是如何引用枚举器的.在foreach的第一个版本中,'num'实际上是绑定到'Current',而不是它返回的结果?
In C# 8.0, Static Local Functions are announced
Can anyone help enlighten me as to why you would want to declare a local function as static?
The reason given in in the article:
to ensure that local function doesn't capture (reference) any variables from the enclosing scope
But:
The example code given in the article is:
int …Run Code Online (Sandbox Code Playgroud)