how to pass any method as a parameter for another function(如何将任何方法作为另一个函数的参数传递)
问题描述
在A班,我有
internal void AFoo(string s, Method DoOtherThing)
{
if (something)
{
//do something
}
else
DoOtherThing();
}
现在我需要能够将 DoOtherThing
传递给 AFoo()
.我的要求是 DoOtherThing
可以有任何返回类型几乎总是无效的签名.B班就是这样的,
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)
{
}
我知道我可以使用 Action
或通过实现委托(如许多其他 SO 帖子中所见)来做到这一点,但如果 B 类中的函数签名未知,如何实现??
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??
推荐答案
你需要传递一个 delegate
实例;Action
可以正常工作:
You need to pass a delegate
instance; Action
would work fine:
internal void AFoo(string s, Action doOtherThing)
{
if (something)
{
//do something
}
else
doOtherThing();
}
如果 BFoo
是无参数的,它将按照您的示例中所写的那样工作:
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"));
这篇关于如何将任何方法作为另一个函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将任何方法作为另一个函数的参数传递


- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01