在C#中处理lambda函数和匿名委托时,我注意到了一些工作和不工作的例子。这里发生了什么事?
class Test : Control {
void testInvoke() {
// The best overloaded method match for 'Invoke' has some invalid arguments
Invoke(doSomething);
// Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type
Invoke(delegate { doSomething(); });
// OK
Invoke((Action)doSomething);
// OK
Invoke((Action)delegate { doSomething(); });
// Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
Invoke(() => doSomething());
// OK
Invoke((Action)(() => doSomething()));
}
void testQueueUserWorkItem() {
// The best overloaded method match for 'QueueUserWorkItem' has some invalid arguments
ThreadPool.QueueUserWorkItem(doSomething);
// OK
ThreadPool.QueueUserWorkItem(delegate { doSomething(); });
// The best overloaded method match for 'QueueUserWorkItem' has some invalid arguments
ThreadPool.QueueUserWorkItem((Action)doSomething);
// No overload for 'doSomething' matches delegate 'WaitCallback'
ThreadPool.QueueUserWorkItem((WaitCallback)doSomething);
// OK
ThreadPool.QueueUserWorkItem((WaitCallback)delegate { doSomething(); });
// Delegate 'WaitCallback' does not take '0' arguments
ThreadPool.QueueUserWorkItem(() => doSomething());
// OK
ThreadPool.QueueUserWorkItem(state => doSomething());
}
void doSomething() {
// ...
}
}
这是很多例子。我想我的问题如下:
Invoke
总是拒绝lambda函数或匿名委托,而ThreadPool.QueueUserWorkItem
却做得很好?ThreadPool.QueueUserWorkItem
接受没有参数的匿名委托,但不接受没有参数的lambda表达式?H 210G 211
发布于 2010-09-29 06:08:54
ThreadPool.QueueUserWorkItem
的签名中有一个特定的委托;Invoke只有Delegate
。Lambda表达式和匿名方法只能转换为特定的委托类型。,
delegate() { ... }
(即显式空参数列表),那么它将无法工作。这种匿名方法的“我不在乎参数”的能力是它们唯一的特性,而lambda表达式却没有。在简单的任务背景下,最容易演示所有这些,海事组织:
// Doesn't work: no specific type
Delegate d = () => Console.WriteLine("Bang");
// Fine: we know the exact type to convert to
Action a = () => Console.WriteLine("Yay");
// Doesn't work: EventHandler isn't parameterless; we've specified 0 parameters
EventHandler e1 = () => Console.WriteLine("Bang");
EventHandler e2 = delegate() { Console.WriteLine("Bang again"); };
// Works: we don't care about parameter lists
EventHandler e = delegate { Console.WriteLine("Lambdas can't do this"); };
https://stackoverflow.com/questions/3822349
复制