I have code:
public delegate int SomeDelegate(int p); public static int Inc(int p) { return p + 1; }
I can cast Inc
to SomeDelegate
or Func<int, int>
:
SomeDelegate a = Inc; Func<int, int> b = Inc;
but I can't cast Inc
to SomeDelegate
and after that cast to Func<int, int>
with usual way like this:
Func<int, int> c = (Func<int, int>)a; // Сompilation error
How I can do it?
Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.
Func<int, int, int> Add = Sum; This Func delegate takes two parameters and returns a single value. In the following example, we use a delegate with three input parameters. int Sum(int x, int y, int z) { return x + y + z; } Func<int, int, int, int> add = Sum; int res = add(150, 20, 30); Console.
Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.
Func<T, TResult> defines a function that accepts one parameter (of type T) and returns an object (of type TResult).
There's a much simpler way to do it, which all the other answers have missed:
Func<int, int> c = a.Invoke;
See this blog post for more info.
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