简体   繁体   English

将函数作为函数参数传递

[英]Passing a function as a function parameter

Unity C# doesn't seem to recognize the Func<> symbol as a function delegate. Unity C#似乎不将Func<>符号识别为函数委托。 So, how can I pass a function as a function parameter? 那么,我如何将函数作为函数参数传递?

I have an idea that Invoke(functionName, 0) might help. 我有一个想法, Invoke(functionName, 0)可能会有所帮助。 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 您可以使用Action来执行此操作

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 或使用lambda

DoSomething(() =>
    {
        // do seomthing when done
    }
);

you can also add parameters eg 你也可以添加参数,例如

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 或者是一个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 特别是对于具有动态参数计数和类型的代表,请查看此帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM