考虑以下代码:
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 Int32 Hi Int32 Hi Int32很明显,我期望看到的是
"Hi String"
、"Hi Single"
和"Hi Int32"
,但实际上不是这样的。为什么在3个方法中都使用了迭代数组的最后一个元素,而非对应的元素呢?你会如何重写代码以达成预期目标?