如何将下面的内容转换为lambda表达式?
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine("Current Thread Id is {0}:",
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("I will be used as Callback");
}
);
最佳答案
你绝对可以将其写为 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 表达式只是语法糖,可用于表达匿名函数 - 编译器会将其转换为匿名函数或表达式树。
关于C# lambda 表达式的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1794920/