相关疑难解决方法(0)

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

请考虑以下代码:

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;
    }

...

}
Run Code Online (Sandbox Code Playgroud)

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

Hi Int32
Hi Int32
Hi Int32  

很显然,我希望 …

c# lambda iterator

23
推荐指数
2
解决办法
9919
查看次数

标签 统计

c# ×1

iterator ×1

lambda ×1