How to create a fully parameterized method delegate in C #?

In C #, we can create delegates using a variety of tools (e.g. Action <>, Func <>, delegate, lambdas, etc.). But when you call these methods, you must specify the parameter values ​​for the called delegate:

delegate int del(int i); del myDelegate = x => x * x; int j = myDelegate(5); 

Is there a way in C # to encapsulate a delegate parameter value WITH WITH? Significantly delays a call to a fully parameterized method? So you do not need to specify parameter values ​​during the call?

For example, something like this invalid code:

 delegate int del(int i); del myDelegate(5) = x => x * x; int j = myDelegate; 

I know that the use case is not immediately obvious. In the case where I am looking now, I have a non-deterministic method that I would like the caller to call the call without having to contain or know the parameters that the method requires. One way to achieve this is to create a class that encapsulates both parameter values ​​and the method delegate, and refers to the caller. But I'm just wondering if there is an alternative, more concise way.

+4
source share
4 answers

This is called currying .

For instance:

 Action curried = () => myFunc(5); 

Or

 Func<int, int, int> multiplier = (x, y) => x * y; Func<int, int> doubler = x => multiplier(x, 2); int eight = doubler(4); 
+12
source

You can always transfer one delegate to another. As SLaks mentioned, this is called currying :

 Func<int, int> square = i => i * i; Func<int> squareFive = () => square(5); int j = squareFive(); 
+1
source
 Func<int, int> myDelegate = x => x * x; Func<int> myDelegate5 = () => myDelegate(5); int j = myDelegate5(); 
+1
source

This can be done intelligently, without lambda, using some common classes and helper functions. I used this approach in some vb.net/vs2005 code. If the goal is to give MethodInvoker, which calls a function with three arguments of types T, U and V, then create a class ParamInvoker <T, U, V> that contains the fields param1, param2 and param3 (like types T, U and V) and Action ( of type Action <T, U, V>) and has a DoIt (void) method that calls Action (param1, param2, param3). Common classes and helper functions are repeated, but the syntax is pretty good. For example (vb syntax, from memory and C # syntax, divination):

  TheMethodInvoker = MakeParamInvoker (AddressOf MyFunction, 5, "Hello")
 or
   TheMethodInvoker = MakeParamInvoker (MyFunction, 5, "Hello")

Assuming MyFunction takes an integer and a string.

0
source

All Articles