相关疑难解决方法(0)

C#中的lambda如何绑定到foreach中的枚举器?

我刚刚遇到了最意想不到的行为.我确信这有一个很好的理由.有人可以帮忙解释一下吗?

考虑以下代码:

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',而不是它返回的结果?

c# foreach lambda

13
推荐指数
1
解决办法
1829
查看次数

Why declare a local function static in C# 8.0

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:

  1. I don't understand why would you want to ensure that?
  2. Is there any other reason or benefits to declare it static? (performance maybe?)

The example code given in the article is:

int …
Run Code Online (Sandbox Code Playgroud)

.net c# static c#-8.0 local-functions

5
推荐指数
3
解决办法
136
查看次数

标签 统计

c# ×2

.net ×1

c#-8.0 ×1

foreach ×1

lambda ×1

local-functions ×1

static ×1