我想在这些功能之间建立联系。
public delegate double Math_calculation(double num);
static double z = 6;
static void Main(string[] args)
{
Math_calculation math ;
Math_calculation math1 = cube, math2 = root, math3 = half;
math = math1;
math += math2;
math += math3;
Console.WriteLine($"solution={math(z)}");
}
public static double root(double x) => z=Math.Sqrt(x);
public static double cube(double x) => z=Math.Pow(x, 3);
public static double half(double x) => z= x / 2;准确输出:3
预期产出:7.34.(平方吨(216)/2)
发布于 2022-06-24 09:08:58
多播委托的返回值是其调用列表中最后一个成员的返回值。这不是您所期望的功能组合。调用列表中的每个方法都使用相同的z参数调用。(另见this post)
你必须自己做函数组合。例如,如下所示:
var composedDelegate = math.GetInvocationList().Aggregate((del1, del2) =>
new Math_calculation(x => (double)del2.DynamicInvoke(del1.DynamicInvoke(x)))
);请注意,以这种方式结束您可以使用的“单播”委托:
Console.WriteLine(((Math_calculation)composedDelegate)(z));
// or
Console.WriteLine(composedDelegate.DynamicInvoke(z));https://stackoverflow.com/questions/72741326
复制相似问题