我可以设置功能吗?带有运行时变量的函数,以忽略在C#中将它们作为参数传递吗? [英] Can I set a Func<> function with runtime variables to omit passing them as parameters in C#?
问题描述
我有一个数值分析程序,为简单起见,它计算类似于以下算法:
I have a numerical analysis program which for simplicity calculates an algorithm similar to:
y = ax^3 + bx^2 + cx + d;
我在运行时计算a,b,c,d的值,并希望传递以下内容等价于 Func< double,double>
。
I calculate the values of a,b,c,d at runtime and would like to pass the following equivalent as a Func<double, double>
. Where I can set a value for X, and get Y.
y = 12x^3 + 13x^2 + 14x + 15;
其中12,13,14,15是运行时计算的数字。
Where 12,13,14,15 are the numbers calculated at runtime.
我意识到这可以通过传递双精度数组来完成,例如: Func< double [],double>
,但是我试图避免传递常量(可能很多)。
I realise this can be done by passing in a double array, like so: Func<double[], double>
but I am trying to avoid passing around the constants (which can be many).
是否可以在运行时在func中设置这些数字?
(最好不对Func本身的a,b,c,d部分进行计算?对a,b,c, d是工作的80%)
(Preferably without making the calculation of a,b,c,d part of the Func<> itself? The calculation of a,b,c,d is 80% of the work)
例如:
a = ...
b = ...
c = ...
Func<x, double> {
((const)a) * x^3 + ((const)b) * x^2 + ((const)c) * x + 15;
}`
对于ABCD的每次评估-我都会评估10次。
For every evaluation of ABCD - I will evaluate 10 x's.
推荐答案
我不确定我是否完全理解您的要求,但是您可以尝试这样的方法吗? / p>
I'm not sure if I understand quite what you are asking, but you could try something like this, perhaps?
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;
}
在这种情况下,您可以拨打 CreateCalculationFunc()
,它将执行一次繁重的计算,并返回可重用的 Func< double,double>
进行变量计算。
In this case, you can just make a call to the CreateCalculationFunc()
, which will do the heavy calculations once, and return a reusable Func<double,double>
for doing your variable calculations.
当然,这可以扩展到任意数量的预先计算的常数和多个变量。
Of course, this is extensible to any amount of pre-calculated constants and more than one variable.
这篇关于我可以设置功能吗?带有运行时变量的函数,以忽略在C#中将它们作为参数传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!