aku
aku

Reputation: 103

How to use delegate as invoke parameter?

How do I give an action delegate as a parameter into invoke:

class C {
    static void A {}
    public static void F(Action action) { action(); }
}

Now I can call F directly:

F(A);

But how do I do the same with an invoke. The following does not compile:

MethodInfo methodInfo = typeof(C).GetMethod("F", BindingFlags.Static |
                                                 BindingFlags.NonPublic);
methodInfo.Invoke(null, new object[]{ A });

Neither does anything else I have tried like:

methodInfo.Invoke(null, new object[]{ C.A });
methodInfo.Invoke(null, new object[]{ () => C.A() });

The compiler says it cannot convert the parameter into "object".

Upvotes: 0

Views: 135

Answers (3)

Antonio Leite
Antonio Leite

Reputation: 480

Specifically, to update label1 in another thread, use the Invoke with arguments with a Lambda statement and the parameters the Func requires.

    Int32 c = 0;
    Int32 d = 0;
    Func<Int32, Int32,Int32> y;


    c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +   
    x2).ToString();  return x1++; }, c,d));
    d++; 

Generically, replace label1 by methodInfo. Use Func. With Action you can't pass arguments.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

Try this

methodInfo.Invoke(null, new object[] { new Action(C.A) });

Upvotes: 1

Alireza
Alireza

Reputation: 10476

First of all your code has a few problems:

1- Method C.A should be declared public in order to be used outside.

2- BindingFlags.NonPublic is preventing to access method 'F' since it is public. Use BindingFlags.Public instead.

Now, you can do as:

methodInfo.Invoke(null, new object[] { new Action(() => { C.A(); }) });

Upvotes: 0

Related Questions