jgauffin
jgauffin

Reputation: 101176

Pass a method to another method

I want to be able to specify a method in another method.

Something like

public class Binder
{
    public void Bind(whatShouldIWriteHere?)
    {
        // do stuff with the MethodInfo
    }
}

so that I can do:

public class A
{
    public void DoIt(string tmp)
    {
    }
}

var binder = new Binder()
binder.Bind<A>(x => x.DoIt);

Instead of:

var method = typeof(A).GetMethod("DoIt");
binder.Bind(method);

Is that possible? :)

Upvotes: 0

Views: 247

Answers (1)

e_ne
e_ne

Reputation: 8469

Pass the method as a delegate and use the Delegate.Method property.

In your case Binder.Bind would be like:

public void Bind(Delegate del)
{
    var info = del.Method;
    //Add your logic here.
}

And to pass a method to it:

var binder = new Binder();
var instance = new A();
binder.Bind(new Action<string>(instance.DoIt))

Upvotes: 2

Related Questions