首页 > 解决方案 > 将函数作为函数参数传递

问题描述

Unity C# 似乎没有将该Func<>符号识别为函数委托。那么,如何将函数作为函数参数传递呢?

我有一个想法Invoke(functionName, 0)可能会有所帮助。但我不确定它是否真的立即调用该函数,或者等待帧结束。还有其他方法吗?

标签: c#unity3d

解决方案


你可以用它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
    }
);

或者,另请参阅代表

特别是对于具有动态参数计数和类型的委托,请查看这篇文章


推荐阅读