是否有任何优雅的方法来"冻结"从方法返回的操作中使用的变量?
只需看看以下代码:
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)
有一个更好的方法吗?
没有一般的方法可以做到这一点 - 但如果你只是被特定的问题困扰foreach,那么有两种选择:
foreach迭代变量的规则发生了变化(对于理智的变量).如果您遇到C#3或4,请捕获循环中声明的局部变量:
foreach(String s in strings)
{
string copy = s;
result.Add(() => Console.WriteLine(copy));
}
Run Code Online (Sandbox Code Playgroud)
这样,循环的每次迭代都会捕获一个单独的变量,该变量永远不会改变值.
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |