在 c# 中将方法作为参数传递

作者:微信公众号:【架构师老卢】
7-4 14:55
46

概述:在 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) {

在 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);  
}

在此示例中:

  • 我们定义了一个带有签名的委托,该签名与我们想要作为参数传递的方法匹配。MyMethodDelegate
  • 该方法将类型的委托作为参数以及字符串后缀。FunctionCallerMyMethodDelegate
  • 我们定义了一个与委托的签名匹配的方法。PrintHello
  • 在该方法中,我们作为参数传递给 。MainPrintHelloFunctionCaller

当您运行该程序时,它将输出:

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);  
}

在此示例中:

  • 该方法将定义签名的函数作为参数。FunctionCallerFunc<string, int>
  • 签名中的第一个参数是我们将为其传递后缀字符串的类型参数,第二个参数是返回值*(如果需要)。Func<string, int>stringint
  • 在该方法中,我们作为参数传递给 。MainPrintHelloFunctionCaller

当您运行该程序时,它将输出:

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);  
}

在此示例中:

  • 该方法将定义签名的 Action 作为参数。FunctionCallerAction<string>
  • 签名中的参数是我们将为其传递后缀字符串的类型参数。Action<string>string
  • 在该方法中,我们作为参数传递给 。MainPrintHelloFunctionCaller

当您运行该程序时,它将输出:

Hello!! passing function as parameter using action

何时使用哪种方法

Delegatemethod 是将 method 作为参数传递的最理想方式,因为它允许您以任何您想要的方式定义委托签名。但是,它始终需要代表签名。

Function方法解决了方法在定义签名方面存在的问题。在 中,您只需要定义函数签名,然后将方法作为参数传递。但是,即使您不需要返回值,它也始终要求您有一个返回值。如果你不需要任何返回值,你总是可以有一些虚拟值,如 .DelegateFunctionreturn 0

Action方法既解决了定义签名的问题,也解决了不需要的返回值的问题。这样,你只需要定义你的Action签名,然后把你的方法作为一个参数传递。但是,如果需要,则不能从函数获得返回值。

结论

总之,将 method 作为参数传递的所有 3 种方法都有其自身的优点和缺点,需要根据用例使用。如果在多个地方需要相同的方法签名,则使用该方法将是理想的选择。但是,如果您正在寻找一种更简单的方法来编写代码,那么 or ways 是更好的选择,您可以根据是否需要返回值来使用它们中的任何一个。

阅读排行