Rene Duchamp
Rene Duchamp

Reputation: 2629

How to pass variable arguments to an Inner method in C#

I have a function in python which uses a function and args(tuple) as input to its inner function: I can replicate these using params and Action InnedMethod(). But how do I wrap the input variables (params) to the InnerMethod here? How can I achieve this.

PYTHON

  def wrap_function(function, args):
    ncalls = [0]
    if function is None:
        return ncalls, None

    def function_wrapper(*wrapper_args):
        ncalls[0] += 1
        return function(*(wrapper_args + args))

    return ncalls, function_wrapper

CSHARP : I am trying to replicate the above Python Function

private double ObjectiveFunctionWrapper(IFunction f, Tuple<List<double>, List<double>> args)
{
    int ncalls = 0;

    Action function_wrapper = () =>
        {
            ncalls = ncalls + 1;
            f(params )
        };
    function_wrapper();
    return ncalls;
}

Upvotes: 1

Views: 405

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180878

To pass a params[] array to a function argument, define your method with an Action<T> argument (instead of IFunction), and use this bit of code:

public Action<T> SetParameters(Action<object[]> action, params object[] parameters)
{
    return delegate { action(parameters) };
}

Upvotes: 2

Related Questions