C# 允许您将方法作为参数传递给函数,从而显著增强代码的灵活性和可重用性。此功能对于实现回调、事件处理程序和运行时行为决定特定操作的策略模式至关重要。本文探讨了实现此目标的多种方法,重点介绍自定义委托、Func<>
和 Action<>
。
目录
使用自定义委托将方法作为参数传递
C# 中的委托充当类型安全的函数指针。当方法签名偏离内置的 Func<>
或 Action<>
委托时,创建自定义委托可以提供更精细的控制和清晰度。考虑一个对数字执行操作然后显示结果的函数,其中操作本身就是一个参数。
// 定义自定义委托
public delegate double MathOperation(double x);
public class Example
{
public static void PerformOperationAndPrint(double num, MathOperation operation)
{
double result = operation(num);
Console.WriteLine($"Result: {result}");
}
public static double Square(double x) => x * x;
public static double Cube(double x) => x * x * x;
public static void Main(string[] args)
{
PerformOperationAndPrint(5, Square); // 输出:Result: 25
PerformOperationAndPrint(5, Cube); // 输出:Result: 125
}
}
MathOperation
充当表示接受一个 double
并返回一个 double
的方法的委托。PerformOperationAndPrint
接受此委托,从而可以使用 Square
、Cube
或任何符合条件的方法。
利用 Func<>
委托
Func<>
是一个泛型委托,表示具有零个或多个输入参数和返回值的方法。其内置特性简化了许多场景。让我们重构之前的示例:
public class Example
{
public static void PerformOperationAndPrint(double num, Func<double, double> operation)
{
double result = operation(num);
Console.WriteLine($"Result: {result}");
}
public static double Square(double x) => x * x;
public static double Cube(double x) => x * x * x;
public static void Main(string[] args)
{
PerformOperationAndPrint(5, Square); // 输出:Result: 25
PerformOperationAndPrint(5, Cube); // 输出:Result: 125
}
}
这以更少的代码实现了相同的结果。Func<double, double>
指定一个接受 double
并返回 double
的方法。泛型类型参数可以适应各种方法签名(例如,Func<int, string>
)。
利用 Action<>
委托
Action<>
是一个泛型委托,用于具有零个或多个输入参数和 void
返回类型(无返回值)的方法。当方法不返回值时使用它。
public class Example
{
public static void PerformAction(string message, Action<string> action)
{
action(message);
}
public static void PrintMessage(string msg) => Console.WriteLine(msg);
public static void PrintMessageToUpper(string msg) => Console.WriteLine(msg.ToUpper());
public static void Main(string[] args)
{
PerformAction("Hello, world!", PrintMessage); // 输出:Hello, world!
PerformAction("Hello, world!", PrintMessageToUpper); // 输出:HELLO, WORLD!
}
}
Action<string>
表示一个接受字符串并且不返回任何值的方法。PerformAction
使用它来执行各种打印操作。
结论
将方法作为参数传递是 C# 的一项强大功能。自定义委托提供最大的控制,而 Func<>
和 Action<>
提供方便的内置解决方案。最佳方法取决于应用程序的具体要求。掌握这些技术是编写更灵活和易于维护的 C# 代码的关键。