[ACCEPTED]-How to pass a function as a parameter in C#?-reflection

Accepted answer
Score: 52

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));
}

Prints "9".

0

Score: 46

Converting a method group, anonymous method 18 or lambda expression to a delegate requires 17 the compiler to know the exact delegate 16 type. However, you could potentially use 15 lambda expressions and captured variables 14 to make this simpler:

public void InvokeMethod(Action action)
{
    action();
}

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

public void Test()
{    
    InvokeMethod(() => Add(2, 3));
}

That basically delays 13 invocation in the normal way, but by wrapping 12 the actual call to Add in a plain Action delegate.

If 11 that doesn't fulfil your requirements, perhaps 10 you can tell us a bit more about what you're 9 really trying to achieve.

EDIT: If this is 8 generated code, you can cast to a Func<...> with 7 the right type arguments - assuming there 6 aren't too many. Other than that, there's 5 no real way of just passing in a method 4 group. There's been occasional calls for 3 an "infoof(...)" operator (like typeof but 2 for members) which would give you a MemberInfo, but 1 that doesn't actually exist.

Score: 4

You should have a delegate first

delegate int Operation(int a, int b)

then it 7 becomes:

public void InvokeMethod(Operation method, object target, object param)
{
    method((int) target, (int) param);
}

No need for any call to Invoke.

As 6 with dbone I'm unsure why you would need 5 a params[] array. Would you clarify the 4 expanded usage for the params?

Also, I'll 3 have to correct something in your question 2 though, because it will cause a compilation 1 error :p

Score: 3

please have a look at using delegates here 5 is a great example

Delegate Example

why are you using reflection? will 4 there ever be a different number of params? or 3 do you know the method signture will remain 2 constant (also remember C# supports the 1 params[] keyword)

params c#

HTH

Bones

Score: 3

Look at Functional Programming Series by Justin Etheredge. You should 1 find solution to your problem there.

Score: 3

This is much simple example, to programmer 2 who already familiar with (C/C++/VB.NET/Python)-style pass 1 function by pointer/ref (with C# delegate):

        delegate void CALLBACK(String s);
        static void Main(string[] args)
        {

            Get("some string", testfunc);

            Util.pause();
        }

        static void Get(String s, CALLBACK x)
        {
            x(s);
        }


        static void testfunc(String s)
        {
            Console.WriteLine(s);
        }
Score: 2

Say If you need to pass the method as parameter 7 as well as you need to catch the return 6 value for further processing . Then the 5 above examples will work fine . But say 4 if you need to pass a method with void return 3 type then you need to create one more version 2 of the InvokeMethod function. Check the 1 example below.

private static T retry<T>(Delegate method, params object[] args)
{
    for (int i = 0; i <= 3; i++)
    {
        try
        {
            return (T)method.DynamicInvoke(args);
        }
        catch (Exception ex)
        {
            if (i == 3)
            {
                logMessage(ex.Message);
            }
            Console.WriteLine("Retry count " + i);
            Thread.Sleep(10);
        }
    }
    return default(T);
}

private static void retry2(Delegate method, params object[] args)
{
    for (int i = 0; i <= 3; i++)
    {
        try
        {
            method.DynamicInvoke(args);
            break;
        }
        catch (Exception ex)
        {
            if (i == 3)
            {
                logMessage(ex.Message);
                //return default(T);
            }
            Console.WriteLine("Retry count " + i);
            Thread.Sleep(10);
        }
    }
}
static bool isSuccess = true;
static void logMessage(string msg)
{
    isSuccess = false;
    Console.WriteLine(msg);
}

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

static void Add2(int a, int b)
{
    int c = a + b;
    Console.WriteLine(c);
}

static void Main(string[] args)
{
    int d = retry<int>(new Func<int, int, int>(Add), 6, 7.7);
    Console.Write("  " + d + "\n"+isSuccess);

    retry2(new Action<int, int>(Add2), 45, 60);

    Console.ReadKey();
}
Score: 1

Something like this ought to work for you:

delegate int MyDelegate(int a, int b);
public int Add(int a, int b) {
    return a + b;
}
public void InvokeMethod(Delegate method, object[] param) {
    Console.WriteLine(method.DynamicInvoke(param));
}
public Form1() {       
    InitializeComponent();
    InvokeMethod(new MyDelegate(Add), new object[] { 1, 2 });
}

Good 1 luck!

More Related questions