Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Method that executes a given Method

Tags:

c#

delegates

func

I am trying to write the following: I would like to write a method "A" which takes as parameter another method "B" as well as an unknown number of parameters for this method B. (params object[] args). Now, inside method A i would like to make a call to B with the parameters args. B will now return an object which I would like A to return as well.

This all sounds a bit strange, therefore I will add some example code:

public object A(Func<object> B, params object[] args)
{
    object x = B.Method.Invoke(args);

    return x;
}

The problem is, that Func does not work like that. Does anyone know a way of doing this?

Regards, Christian

like image 633
Christian Avatar asked Jan 24 '11 10:01

Christian


2 Answers

void Main()
{
    Func<int> m1=()=>1;
    Console.WriteLine(A(m1));

    Func<int,int> m2=i=>i;
    Console.WriteLine(A(m2,55));
}

object A(Delegate B,params object[] args)
{

    return B.Method.Invoke(B.Target,args);
}

...goodbye type-safety

like image 169
spender Avatar answered Sep 30 '22 00:09

spender


Func<object> is a delegate for a method that takes no arguments and returns object. If you change it to Func<object,object>, it will take an argument and return object:

public object A(Func<object, object> B, params object[] args)
{
    object x = B(args);

    return x;
}
like image 36
Fredrik Mörk Avatar answered Sep 30 '22 02:09

Fredrik Mörk