为什么代码不能编译

时间:2015-11-22 21:53:58

标签: c#

为什么代码不能编译,当它执行相同的操作时。

错误讯息:

  

无法从System.Action转换为System.Threading.ThreadStart。

代码:

// Compiles and works
for (int i = 0; i < 100000; i++)
{
    Thread t = new Thread(() => {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(100); Interlocked.Increment(ref Count);
    });
    t.Start();
}

// doesn't compile
Action action = () => {
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(100);
    Interlocked.Increment(ref Count);
};

for (int i = 0; i < 100000; i++)
{
    Thread t = new Thread(action);
}

1 个答案:

答案 0 :(得分:5)

那是因为从具有正确签名的lambda隐式转换为ThreadStart委托,而不是从Action委托转移到ThreadStart委托。但是存在显式转换:

Thread t = new Thread(new ThreadStart(action));

lambda表达式没有类型,但它与具有匹配参数和返回类型的任何委托兼容。另一方面,委托类型不能隐式地相互转换,但如果它们具有兼容的签名,则可以显式转换。