gpt4 book ai didi

c# - 在 lambda 表达式中使用 foreach 循环的迭代器变量 - 为什么会失败?

转载 作者:IT王子 更新时间:2023-10-29 04:29:50 25 4
gpt4 key购买 nike

考虑以下代码:

public class MyClass
{
public delegate string PrintHelloType(string greeting);


public void Execute()
{

Type[] types = new Type[] { typeof(string), typeof(float), typeof(int)};
List<PrintHelloType> helloMethods = new List<PrintHelloType>();

foreach (var type in types)
{
var sayHello =
new PrintHelloType(greeting => SayGreetingToType(type, greeting));
helloMethods.Add(sayHello);
}

foreach (var helloMethod in helloMethods)
{
Console.WriteLine(helloMethod("Hi"));
}

}

public string SayGreetingToType(Type type, string greetingText)
{
return greetingText + " " + type.Name;
}

...

}

调用 myClass.Execute() 后,代码打印出以下意外响应:

Hi Int32Hi Int32Hi Int32  

显然,我期望 "Hi String""Hi Single""Hi Int32",但显然不是案子。为什么在所有 3 种方法中都使用了迭代数组的最后一个元素,而不是相应的方法?

您将如何重写代码以实现预期目标?

最佳答案

欢迎来到闭包和捕获变量的世界:)

Eric Lippert 对此行为有深入的解释:

基本上,捕获的是循环变量,而不是它的值。要获得您认为应该获得的东西,请执行以下操作:

foreach (var type in types)
{
var newType = type;
var sayHello =
new PrintHelloType(greeting => SayGreetingToType(newType, greeting));
helloMethods.Add(sayHello);
}

关于c# - 在 lambda 表达式中使用 foreach 循环的迭代器变量 - 为什么会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3168375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com