这不行吗?请注意,扩展方法必须在公共静态类中,并且方法本身必须是静态的。
public static class FunctionalExtensions
{
public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
{
return x => f(g(x));
}
}
class Program
{
static void Main(string[] args)
{
Func<double, double>
f1 = Square, // Func<double, double> is a delegate type so we have to create
g1 = AddOne, // an instance for both f and g
h1 = f1.Compose(g1); // This is a Func<double, double> now, (i.e. h(X) = f(g(x)) )
// To call new function do this
double result1 = h1(5.0);
Func<double, double>
f2 = x => x*x,
g2 = x => x + 1,
h2 = f2.Compose(g2);
// To call new function do this
double result2 = h2(5.0);
}
public static double Square(double x)
{
return x * x;
}
public static double AddOne(double x)
{
return x + 1;
}
}
还要注意 f1: double -> double 和 g1: double -> double。
在撰写功能中
f: V -> U 和 g: U -> T
所以 fg: V -> T
换句话说,在我的示例中,并非所有类型都必须是双精度的。您只需确保函数 f(外部函数)的域包括函数 g(内部函数)的范围。在编程中,这意味着 g 的返回类型需要与 f 的参数类型相同(或隐式转换为)。