System.Threading.Thread 类有 the constructors :
public class Thread
{
public Thread (System.Threading.ThreadStart start);
}
为什么 System.Threading.ThreadStart start 是 delegate :
public delegate void ThreadStart();
实例化委托的语法是:
ThreadStart myDelegate = new ThreadStart(printer.Print0);
// C#2 add this sugar syntax, but it's same instruction that below
ThreadStart myDelegate = printer.Print0;
那么这个语法是等价的:
Thread thread = new Thread(new ThreadStart(printer.Print0));
Thread thread2 = new Thread(printer.Print0);
只是第二次在 C#2 中使用糖语法添加。
在 C#3 中,lambda 以一种新的方式添加到语言中来声明委托:
ThreadStart myDelegate = () => { printer.Print0 };
就像是 :
public class MyLambda
{
public Printer printer;
void Run()
{
printer.Print0();
}
}
ThreadStart myDelegate = new MyLambda() { printer = printer }.Run;
不完全像第一个例子,因为从技术上讲它调用了一个中间方法。但唯一的感知差异是调用堆栈......我认为这种语法相似。
从您的评论中回答您的问题:
使用显式调用和 lambda 表达式有什么好处吗?
不,这只是不同的语法。您可以选择您喜欢的一个而无需其他考虑。