在C#中,确实可以将一个方法作为参数传递给另一个方法。这种技术通常称为“委托”(Delegates)或“Lambda表达式”。以下是几种常见的方法来实现这一点:
如果你不想显式定义一个委托类型,可以使用匿名方法。
public void MethodA(Action<int> action)
{
action(10);
}
// 使用匿名方法
MethodA(param => Console.WriteLine($"Anonymous method called with {param}"));
Lambda表达式提供了一种更简洁的方式来定义匿名方法。
public void MethodA(Action<int> action)
{
action(10);
}
// 使用Lambda表达式
MethodA(param => Console.WriteLine($"Lambda called with {param}"));
如果你需要返回值,可以使用Func<T, TResult>
委托。
public int MethodA(Func<int, int> func)
{
return func(10);
}
public int MethodB(int param)
{
return param * 2;
}
// 使用
int result = MethodA(MethodB);
Console.WriteLine(result); // 输出 20
通过上述方法,你可以在C#中灵活地将一个方法作为参数传递给另一个方法,从而提高代码的可维护性和扩展性。
领取专属 10元无门槛券
手把手带您无忧上云