如何将任何方法作为另一个函数的参数传递
本文关键字:另一个 函数 参数传递 任何 方法 | 更新日期: 2023-09-27 18:18:53
在A类中,我有
internal void AFoo(string s, Method DoOtherThing)
{
if (something)
{
//do something
}
else
DoOtherThing();
}
现在我需要能够将DoOtherThing
传递给AFoo()
.我的要求是DoOtherThing
可以具有返回类型几乎总是无效的任何签名。B类的类似东西,
void Foo()
{
new ClassA().AFoo("hi", BFoo);
}
void BFoo(//could be anything)
{
}
我知道我可以通过Action
或通过实施代表来做到这一点(如许多其他 SO 帖子中看到的那样(,但如果 B 类中函数的签名未知,如何实现这一目标?
您需要传递一个delegate
实例; Action
可以正常工作:
internal void AFoo(string s, Action doOtherThing)
{
if (something)
{
//do something
}
else
doOtherThing();
}
如果BFoo
是无参数的,它将按照您的示例中编写的方式工作:
new ClassA().AFoo("hi", BFoo);
如果需要参数,则需要提供它们:
new ClassA().AFoo("hi", () => BFoo(123, true, "def"));
如果需要返回值,请使用 Action 或 Fenc。
行动:http://msdn.microsoft.com/en-us/library/system.action.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();
}
用法:
var ReturnValue = Runner(() => GetUser(99));
我使用它在我的 MVC 站点上进行错误处理。