将以下内容转换为lambda表达式的方法是什么?
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine("Current Thread Id is {0}:",
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("I will be used as Callback");
}
);
答案 0 :(得分:4)
你绝对可以把它写成lambda表达式:
// The underscore is simply a placeholder for the "state"
// parameter that the WaitCallback delegate expects - you could
// use any character but you must specify one as lamba expressions cannot
// omit parameters like anonymous functions can.
ThreadPool.QueueUserWorkItem((_) =>
{
Console.WriteLine("Current Thread Id is {0}:",
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("I will be used as Callback");
});
但请记住,lambda表达式在源代码之外没有任何意义。 C#编译器会将你的lambda表达式转换回你现在拥有的代码。
lambda表达式只是可用于表示匿名函数的语法糖 - 编译器会将其转换为匿名函数或表达式树。