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"));
这篇关于如何将任何方法作为另一个函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将任何方法作为另一个函数的参数传递


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01