我知道很多问题已经在C#关闭中提出并回答或讨论过。但是,请饶了我一点点时间对我的小实验......关于C#关闭的另一个问题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var timer = new Timer(500))
{
timer.AutoReset = false;
GetFunc2(timer, 0);
// GetFunc3(timer, 0);
timer.Start();
Console.ReadLine();
}
}
static void GetFunc2(Timer timer, int i)
{
for (; i < 5; ++i)
{
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i);
};
}
}
static void GetFunc3(Timer timer, int i)
{
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
}
}
}
通过调用Main
GetFunc2
和GetFunc3
独立,我们可以看到输出是不同的,虽然看起来GetFun3
仅仅像GetFunc2
简单地扩大。任何人都知道为什么?我认为ildasm可以揭示不同的生成代码,但我确实想知道为什么。测试VS2012 Pro,.net 4.5。
您可能希望为我们提供您看到的不同输出,并非每个人都可以访问C#编译器 – Lukazoid 2013-02-18 00:13:31
请给这个更精确的标题。按照它的规定,这个问题是关于一段代码的,你需要更一般地阐述它,所以我投票结果太过本地化。 – djechlin 2013-02-18 00:28:48
@djechlin被问到的问题非常明确,这是一个普遍的原则。如果你能想出更好的标题,请随时编辑问题。 – 2013-02-18 00:31:32