Note that there are some explanatory texts on larger screens.

plurals
  1. PO.NET4: How to apply dynamic binding to anonymous delegates with returns?
    text
    copied!<pre><code>class MyClass { public event Action&lt;string&gt; OnAction; public event Func&lt;string, int&gt; OnFunc; } class Program { static void Main(string[] args) { MyClass mc = new MyClass(); /// I need to handle arbitrary events. /// But I see no way to create anonymous delegates in runtime /// with arbitrary returns and parameters. So I choosed to /// create multiple “signatures” with different parameter /// number (up to 10) and different returns (either the Action or /// Func). While Actions&lt;&gt; work pretty well, the Funcs&lt;&gt; do not. Action&lt;dynamic&gt; someAction = delegate(dynamic p1) { }; Func&lt;dynamic, dynamic&gt; someFunc = delegate(dynamic p1) { return 42;}; // OK mc.OnAction += someAction; // Error: “Cannot implicitly convert type 'System.Func&lt;dynamic,dynamic&gt;' // to 'System.Func&lt;string,int&gt;'” mc.OnFunc += someFunc; // It doesn't work this way as well (the same error message): // dynamic someFunc = new Func&lt;dynamic, dynamic&gt;((dynamic n1) =&gt; { return 42; }); // Let's try another way // 1: // Cannot convert anonymous method to delegate type 'System.Func&lt;string,int&gt;' // because the parameter types do not match the delegate parameter types. // 2 (even more funny): // Parameter 1 is declared as type 'dynamic' but should be 'string'. mc.OnFunc += delegate(dynamic p1) { return 42; }; } } </code></pre> <p>Why does it work for actions and doesn't for functions? In other words, I just would like to know why <code>Action&lt;dynamic&gt; → Action&lt;string&gt;</code> is ok while <code>Func&lt;dynamic,dynamic&gt; → Func&lt;string, int&gt;</code> is not. Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload