【问题标题】:cant find code output and can understand why找不到代码输出,可以理解为什么
【发布时间】:2017-02-13 12:27:09
【问题描述】:

嗨,我有一个代码,我不明白他的输出应该是什么。

代码如下:

delegate void Employee();
static void Main()
{
                IList employees= new List<Employee>();

                for(int i=0;i<3;i++)
                {
                    employee.Add( () => Console.Write(i));
                }
                foreach(var employee in employees)
                {
                    employee();
                }
}

谁能帮我解决这个问题?输出是什么?你是如何找到它的?

【问题讨论】:

  • 嗯...把代码粘贴到Visual Studio中并执行?
  • Console.Write() 将输出到控制台。也许这有帮助:Seeing the console's output in Visual Studio 2010?
  • 您将打印333,但您需要将其声明为IList&lt;Employee&gt; 而不是IList
  • @vc74:它们在foreach 中被调用,但它们将使用i 的最后一个值
  • 如果你不想要这种行为,而是i 的实际值,你不应该“访问这个修改后的闭包”(resharper 警告),而是在你分配值的循环中使用局部变量i

标签: c#


【解决方案1】:

您的代码无法编译

我想这就是你的意思:

delegate void Employee(); // Note that this is equivalent to the Action delegate

static void Main(string[] args)
{
    IList employees = new List<Employee>();

    for (int i = 0; i < 3; i++)
    {
        employees.Add(new Employee(() => Console.Write(i)));
    }

    foreach (Employee employee in employees)
    {
        employee();
    }
}

正如 Tim 指出的那样打印 333,因为您的 3 个代表的 i 变量是 captured

Employee 并不是代表的理想名称,起初我以为您有一个名为 Employee 的类和另一个名为 employee 的集合,但您似乎唯一需要的是一个委托实例的集合。

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多