1

在下面的代码中,参数 's' 代表什么?我们可以不只是省略's',因为它没有在方法中使用,所以我们有一个没有参数的匿名方法,如 () => ...?

ThreadPool.QueueUserWorkItem((s)=> 
{
 Console.WriteLine("Working on a thread from threadpool");
});

更新 1:

根据接受的答案,匿名方法只是普通 WaitCallback 委托方法的替代品,如下面的 ocd 中的委托方法,QueueUserWorkItem 需要它作为参数。因此,'s' 应该是对象类型,因为它是 ThreadProc 方法的参数。

void ThreadProc(Object stateInfo) {
   // No state object was passed to QueueUserWorkItem, so  
   // stateInfo is null.
    Console.WriteLine("Working on a thread from threadpool");
 }
4

1 回答 1

4

匿名委托的 C# 2.0 语法允许省略参数列表,在这种情况下,它将匹配任何(ref非非out)参数集并忽略它们。

ThreadPool.QueueUserWorkItem(delegate {
   Console.WriteLine("Working on a thread from threadpool");
});

注意delegate {}不同于delegate () {}

另一方面,如果没有提供参数列表,则 lambda 语法不起作用。

于 2014-09-12T05:17:16.813 回答