I have the following delegate defined:
public delegate object MyDelegate(dynamic target);
And I have a Func<dynamic, object>
object:
Func<dynamic, object> myFunc
How can I convert myFunc
to MyDelegate
?
I have tried these instructions, none of them worked:
MyDelegate myDeleg = myFunc;
MyDelegate myDeleg = (MyDelegate) myFunc;
MyDelegate myDeleg = myFunc as MyDelegate;
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.
A Func in C# is a way to define a method in-line that has a return value. There is a similar concept of an Action that doesn't have a return value, but we'll get to that in a sec. The return value's type is always the last generic parameter on the Func 's definition.
A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.
Advantages to using them in design:Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate [Func<T,bool>] to filter on, without having to write new code in the Where method.
You can wrap the existing delegate:
(MyDelegate)(x => myFunc(x))
Or equivalently:
MyDelegate myDeleg = x => myFunc(x);
This causes a small performance loss on each invocation but the code is very simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With