我可以使用运行时变量设置Func <>函数,以省略在C#中将它们作为参数传递吗?

Jar*_*oad 1 c# delegates runtime func

我有一个数值分析程序,为简单起见计算类似于以下的算法:

y = ax^3 + bx^2 + cx + d;
Run Code Online (Sandbox Code Playgroud)

我在运行时计算a,b,c,d的值,并希望将以下等效项传递给a Func<double, double>.我可以在哪里设置X的值,并获得Y.

y = 12x^3 + 13x^2 + 14x + 15; 
Run Code Online (Sandbox Code Playgroud)

其中12,13,14,15是运行时计算的数字.

我意识到这可以通过传入一个双数组来完成,就像这样:Func<double[], double> 但我试图避免传递常量(可能很多).

有没有办法在运行时在func中设置这些数字?

(最好不要计算func <>本身的a,b,c,d部分?a,b,c,d的计算是工作的80%)

例如:

a = ...

b = ...

c = ...

Func<x, double> {
     ((const)a) * x^3 +   ((const)b) * x^2 +   ((const)c) * x + 15;
}`
Run Code Online (Sandbox Code Playgroud)

对于ABCD的每次评估 - 我将评估10 x.

Ale*_*lex 11

我不确定我是否理解你的要求,但是你可以尝试这样的事情吗?

Func<double, double> CreateCalculationFunc()
{
    double a = heavy calculation;
    double b = heavy calculation;
    double c = heavy calculation;
    double d = heavy calculation;

    Func<double, double> calculation = (x) =>
    {
        // You can use the constants in here without passing them as parameters
        return x * (a * b / c - d);
    };

    return calculation;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以调用CreateCalculationFunc()一次,这将执行繁重的计算一次,并返回一个可重用Func<double,double>的进行变量计算.

当然,这可以扩展到任何数量的预先计算的常量和多个变量.