简体   繁体   English

如何将任何方法作为另一个函数的参数传递

[英]how to pass any method as a parameter for another function

In class A, I have 在A班,我有

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

Now I need to be able to pass DoOtherThing to AFoo() . 现在,我需要能够将DoOtherThing传递给AFoo() My requirement is that DoOtherThing can have any signature with return type almost always void. 我的要求是, DoOtherThing可以具有返回类型几乎总是无效的任何签名。 Something like this from Class B, 来自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?? 我知道我可以使用Action或通过实现委托来做到这一点(如在许多其他SO帖子中所看到的),但是如果B类中函数的签名未知,又如何实现?

You need to pass a delegate instance; 您需要传递一个delegate实例。 Action would work fine: Action会很好:

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: 如果BFoo是无参数的,它将按照您的示例编写:

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

If it needs parameters, you'll need to supply them: 如果需要参数,则需要提供它们:

new ClassA().AFoo("hi", () => BFoo(123, true, "def"));

Use an Action or Func if you need a return value. 如果你需要一个返回值,使用操作FUNC。菜单

Action: http://msdn.microsoft.com/en-us/library/system.action.aspx 行动: http//msdn.microsoft.com/en-us/library/system.action.aspx

Func: http://msdn.microsoft.com/en-us/library/bb534960.aspx 功能: http//msdn.microsoft.com/en-us/library/bb534960.aspx

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. 我将其用于MVC网站上的错误处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM