将函数作为函数参数传递 [英] Passing a function as a function parameter
问题描述
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
}
);
或者也可以参见代表
尤其是对于具有动态参数计数和类型的代表来说,请查看这篇文章 >
Unity C# doesn't seem to recognize the Func<>
symbol as a function delegate. So, how can I pass a function as a function parameter?
I have an idea that Invoke(functionName, 0)
might help. But I am not sure whether it actually invokes the function instantly, or waits for the end of the frame. Is there another way?
You can use Action
to do that
using System;
// ...
public void DoSomething(Action callback)
{
// do something
callback?.Invoke();
}
and either pass in a method call like
private void DoSomethingWhenDone()
{
// do something
}
// ...
DoSomething(DoSomethingWhenDone);
or using a lambda
DoSomething(() =>
{
// do seomthing when done
}
);
you can also add parameters e.g.
public void DoSomething(Action<int, string> callback)
{
// dosomething
callback?.Invoke(1, "example");
}
and again pass in a method like
private void OnDone(int intValue, string stringValue)
{
// do something with intVaue and stringValue
}
// ...
DoSomething(OnDone);
or a lambda
DoSomething((intValue, stringValue) =>
{
// do something with intVaue and stringValue
}
);
Alternatively also see Delegates
and especially for delegates with dynamic parameter count and types check out this post
这篇关于将函数作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!