c# - 将函数作为函数参数传递
问题描述
Unity C# 似乎没有将该Func<>
符号识别为函数委托。那么,如何将函数作为函数参数传递呢?
我有一个想法Invoke(functionName, 0)
可能会有所帮助。但我不确定它是否真的立即调用该函数,或者等待帧结束。还有其他方法吗?
解决方案
你可以用它Action
来做到这一点
using System;
// ...
public void DoSomething(Action callback)
{
// do something
callback?.Invoke();
}
并传入一个方法调用,如
private void DoSomethingWhenDone()
{
// do something
}
// ...
DoSomething(DoSomethingWhenDone);
或使用 lambda
DoSomething(() =>
{
// do seomthing when done
}
);
您还可以添加参数,例如
public void DoSomething(Action<int, string> callback)
{
// dosomething
callback?.Invoke(1, "example");
}
并再次传入类似的方法
private void OnDone(int intValue, string stringValue)
{
// do something with intVaue and stringValue
}
// ...
DoSomething(OnDone);
或 lambda
DoSomething((intValue, stringValue) =>
{
// do something with intVaue and stringValue
}
);
或者,另请参阅代表
特别是对于具有动态参数计数和类型的委托,请查看这篇文章
推荐阅读
- react-native - 反应导航中 Stack 和 Swtich Navigator 之间的嵌套导航器之间的导航
- python - Virtualbox上的Python脚本非常慢
- javascript - 以编程方式附加脚本时未捕获的异常
- java - 如何通过共享对象正确使用信号?
- python - 使用 PySpark 中的列值组合查找最小和最大范围
- file - 如何提交以强制执行非英文文件?
- ios - 在 React Native 中使用 nativeID/使用 RCTRootView 子视图的正确方法是什么?
- python - 启动 cmd 并在创建的 cmd 实例中运行多个命令
- javascript - HTML FORM - 使用 onchange() 更改部分只读字符串字段
- javascript - 从动态表单字段创建对象列表