naw*_*fal 1 c# methods delegates parameter-passing
在A级,我有
internal void AFoo(string s, Method DoOtherThing)
{
if (something)
{
//do something
}
else
DoOtherThing();
}
Run Code Online (Sandbox Code Playgroud)
现在我需要能够传递DoOtherThing
给AFoo()
.我的要求是,DoOtherThing
任何具有返回类型的签名几乎总是无效的.来自B级的东西,
void Foo()
{
new ClassA().AFoo("hi", BFoo);
}
void BFoo(//could be anything)
{
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过Action
或通过实现代表来实现这一点(如许多其他SO帖子中所见)但如果B类中的函数签名未知,怎么能实现呢?
你需要传递一个delegate
实例; Action
会工作正常:
internal void AFoo(string s, Action doOtherThing)
{
if (something)
{
//do something
}
else
doOtherThing();
}
Run Code Online (Sandbox Code Playgroud)
如果BFoo
是无参数的,它将按照您的示例中的说明工作:
new ClassA().AFoo("hi", BFoo);
Run Code Online (Sandbox Code Playgroud)
如果它需要参数,您需要提供它们:
new ClassA().AFoo("hi", () => BFoo(123, true, "def"));
Run Code Online (Sandbox Code Playgroud)