在 C# 中,可以使用 或 将方法作为参数传递。将方法作为参数传递类似于 C 或 C++ 中的函数指针,允许您定义对具有特定签名的方法的引用。让我们一一介绍每种方法:
public delegate void MyMethodDelegate(string suffix);
void PrintHello(string suffix)
{
Debug.Log("Hello!! passing function as parameter using " + suffix);
}
void FunctionCaller(MyMethodDelegate myMethod)
{
myMethod("delegate");
}
void Main()
{
FunctionCaller(PrintHello);
}
在此示例中:
当您运行该程序时,它将输出:
Hello!! passing function as parameter using delegate
int PrintHello(string suffix)
{
Debug.Log("Hello!! passing function as parameter using " + suffix);
return 0;
}
void FunctionCaller(Func<string, int> myMethodName)
{
var returnValue = myMethodName("function");
Debug.Log("Return value from the function is " + returnValue);
}
void Main()
{
FunctionCaller(PrintHello);
}
在此示例中:
当您运行该程序时,它将输出:
Hello!! passing function as parameter using function
Return value from the function is 0
void PrintHello(string suffix)
{
Debug.Log("Hello!! passing function as parameter using " + suffix);
}
void FunctionCaller(Action<string> myMethodName)
{
myMethodName("action");
}
void Main()
{
FunctionCaller(PrintHello);
}
在此示例中:
当您运行该程序时,它将输出:
Hello!! passing function as parameter using action
Delegatemethod 是将 method 作为参数传递的最理想方式,因为它允许您以任何您想要的方式定义委托签名。但是,它始终需要代表签名。
Function方法解决了方法在定义签名方面存在的问题。在 中,您只需要定义函数签名,然后将方法作为参数传递。但是,即使您不需要返回值,它也始终要求您有一个返回值。如果你不需要任何返回值,你总是可以有一些虚拟值,如 .DelegateFunctionreturn 0
Action方法既解决了定义签名的问题,也解决了不需要的返回值的问题。这样,你只需要定义你的Action签名,然后把你的方法作为一个参数传递。但是,如果需要,则不能从函数获得返回值。
总之,将 method 作为参数传递的所有 3 种方法都有其自身的优点和缺点,需要根据用例使用。如果在多个地方需要相同的方法签名,则使用该方法将是理想的选择。但是,如果您正在寻找一种更简单的方法来编写代码,那么 or ways 是更好的选择,您可以根据是否需要返回值来使用它们中的任何一个。