优雅的方式来冻结封闭

And*_*eas 1 c# closures

是否有任何优雅的方法来"冻结"从方法返回的操作中使用的变量?

只需看看以下代码:

static void Main(String[] args) 
{
    foreach(Action a in ClosureTrap("a", "b")) 
    {
        a();
    }
}

static List<Action> ClosureTrap(params String[] strings) 
{
    List<Action> result = new List<Action>();
    foreach(String s in strings) 
    {
        result.Add(() => Console.WriteLine(s));
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

此代码将向控制台写入两行,两行都包含"b".其原因并不难找到:ClosureTrap中"s"的最后一个值是"b".

是否有任何优雅的方法可以在控制台上输出两行"a"和"b"作为输出?

目前我正在使用另一种方法来创建委托.但通过这样做,封闭件失去了很多优雅:

static List<Action> ClosureTrap(params String[] strings) 
{
    List<Action> result = new List<Action>();
    foreach(String s in strings) 
    {
        result.Add(Freeze(s));
    }
    return result;
}

static Action Freeze(String s) 
{
    return () => Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

Jon*_*eet 5

没有一般的方法可以做到这一点 - 但如果你只是被特定的问题困扰foreach,那么有两种选择: