how to pass any method as a parameter for another

2020-07-27 03:47发布

In class A, I have

internal void AFoo(string s, Method DoOtherThing)
{
    if (something)
    {
        //do something
    }
    else
        DoOtherThing();
}

Now I need to be able to pass DoOtherThing to AFoo(). My requirement is that DoOtherThing can have any signature with return type almost always void. Something like this from Class B,

void Foo()
{
    new ClassA().AFoo("hi", BFoo);
}

void BFoo(//could be anything)
{

}

I know I can do this with Action or by implementing delegates (as seen in many other SO posts) but how could this be achieved if signature of the function in Class B is unknown??

3条回答
混吃等死
2楼-- · 2020-07-27 04:14
Juvenile、少年°
3楼-- · 2020-07-27 04:20
public static T Runner<T>(Func<T> funcToRun)
{
    //Do stuff before running function as normal
    return funcToRun();
}

Usage:

var ReturnValue = Runner(() => GetUser(99));

I use this for error handling on my MVC site.

查看更多
SAY GOODBYE
4楼-- · 2020-07-27 04:35

You need to pass a delegate instance; Action would work fine:

internal void AFoo(string s, Action doOtherThing)
{
    if (something)
    {
        //do something
    }
    else
        doOtherThing();
}

If BFoo is parameterless it will work as written in your example:

new ClassA().AFoo("hi", BFoo);

If it needs parameters, you'll need to supply them:

new ClassA().AFoo("hi", () => BFoo(123, true, "def"));
查看更多
登录 后发表回答