c# - How do delegate/lambda typing and coercion work? -
i've noticed examples of things work , don't work when dealing lambda functions , anonymous delegates in c#. what's going on here?
class test : control { void testinvoke() { // best overloaded method match 'invoke' has invalid arguments invoke(dosomething); // cannot convert anonymous method type 'system.delegate' because not delegate type invoke(delegate { dosomething(); }); // ok invoke((action)dosomething); // ok invoke((action)delegate { dosomething(); }); // cannot convert lambda expression type 'system.delegate' because not delegate type invoke(() => dosomething()); // ok invoke((action)(() => dosomething())); } void testqueueuserworkitem() { // best overloaded method match 'queueuserworkitem' has invalid arguments threadpool.queueuserworkitem(dosomething); // ok threadpool.queueuserworkitem(delegate { dosomething(); }); // best overloaded method match 'queueuserworkitem' has invalid arguments threadpool.queueuserworkitem((action)dosomething); // no overload 'dosomething' matches delegate 'waitcallback' threadpool.queueuserworkitem((waitcallback)dosomething); // ok threadpool.queueuserworkitem((waitcallback)delegate { dosomething(); }); // delegate 'waitcallback' not take '0' arguments threadpool.queueuserworkitem(() => dosomething()); // ok threadpool.queueuserworkitem(state => dosomething()); } void dosomething() { // ... } }
well that's lot of examples. guess questions following:
why
invoke
refuse lambda function or anonymous delegate, yetthreadpool.queueuserworkitem
fine?what heck "cannot convert anonymous method type 'system.delegate' because not delegate type" mean anyway?
why
threadpool.queueuserworkitem
accept anonymous delegate no parameters, not lambda expression no parameters?
threadpool.queueuserworkitem
has specific delegate in signature; invoke hasdelegate
. lambda expressions , anonymous methods can converted specific delegate type.it's bad error message. means, "i don't know delegate type you're trying convert to."
you're using anonymous method without parameter list @ all can converted delegate type doesn't use out/ref parameters. if tried
delegate() { ... }
(i.e. explicitly empty parameter list) wouldn't work. "i don't care parameters" ability of anonymous methods only feature have lambda expressions don't.
it's easiest demonstrate of in context of simple assignments, imo:
// doesn't work: no specific type delegate d = () => console.writeline("bang"); // fine: know exact type convert action = () => 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: don't care parameter lists eventhandler e = delegate { console.writeline("lambdas can't this"); };
Comments
Post a Comment