Method for passing calls with already specified arguments

I would like to call method A with parameters already specified from another method. So I want to pass the method call and arguments as a parameter to MethodB, and once it has done some processing, call MethodA with the arguments provided.

I know I can pass the call as method B as a delegate parameter and then pass parameters like this:

static void Main( string[] args )
        {
            MethodB(1, 2, Add);

            Console.ReadLine();
        }

        public static void Add(int i, int j)
        {
            Console.WriteLine(i+j);
        }

static public class DelegateWithDelegateParameter
    {
        public static void MethodB(int param1, int param2, Action<int, int> dAction)
        {
            dAction(param1, param2);
        }
    }

      

It is surprising if it is possible to do this with the parameters already specified, and not with the passing of ParamA parameters, ParamB in MethodB from Main is already specified. It was just interesting. Hope this makes sense, please let me know if you want more details.

+3


source to share


3 answers


If I follow what you are asking to get what you want, you need to wrap your call to add to the delegate that contains its parameters. This is easily done with lamda :

static void Main( string[] args )
{
    MethodB(() => Add(1, 2));

    Console.ReadLine();
}

public static void Add(int i, int j)
{
    Console.WriteLine(i+j);
}

static public class DelegateWithDelegateParameter
{
    public static void MethodB(Action dAction)
    {
        dAction();
    }
}

      



The operator () => Add(1,2)

creates a new delegate Action

that is defined to be called Add()

with parameters 1,2

.

+3


source


I think what you want is:



static object InvokeMethod(Delegate method, params object[] args){
    return method.DynamicInvoke(args);
}

static int Add(int a, int b){
    return a + b;
}

static void Test(){
    Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4));
}

      

0


source


You can do this through the Delegate. first declare a delegate and bind it to it like

public delegate void adddelegate(int a, int b);
class Program
{
    static void Main(string[] args)
    {
        adddelegate adddel = new adddelegate(Add);

        DelegateWithDelegateParameter.MethodB(1, 2, adddel);

        Console.ReadLine();
    }

    public static void Add(int i, int j)
    {
        Console.WriteLine(i + j);
    }
}

static public class DelegateWithDelegateParameter
{
    public static void MethodB(int param1, int param2, adddelegate dAction)
    {
        dAction(param1, param2);
    }
}

      

0


source







All Articles