如何最好地捕捉Func<可能产生的副作用>在C#中?对此有最佳实践吗



我使用的数学库中有代码,无法更改。我正在使用的数学库中的函数迭代使用近似函数,如下所示。

public double Calculate(double startInput, Func<double, double> approximationFunc)
{
var result = 0d;
var max = 10;
for (int i = 0; i < max; i++)
{
result = approximationFunc(startInput);
//do some checks ...
startInput =DoSomething();
}
return result;
}

然而,在approximationFunc中,我使用的是"在现实中",我必须计算除双重结果之外的其他内容,并且我需要重复使用这些结果。我唯一想到的是:

public void BusinessLogic(double startInput)
{
MyOtherResult myOtherResult = null;
double myFunction(double input)
{
var result = ComputeMyResult(input);
myOtherResult = ComputeMyOtherResult(result, someOtherStuff);
return result;
}
var approximationResult = Calculate(startInput, myFunction);
var myOtherApproximationResult = myOtherResult;
// Do other stuff...
}

然而,我不确定这是否是获得"其他结果"的最佳方式,也不确定是否有无副作用的方式。我提出的解决方案之所以有效,是因为我知道我使用的库会迭代地应用这个函数,这并不理想。你将如何在C#中解决这个问题?我已经绞尽脑汁两天了,但它一直不响。

委托可以(通常也确实(有一个目标对象。因此:您可以有意地将目标对象作为逻辑所需的状态包装器。例如:

class MyState {
public double MyFunc(double x) {
// do whatever here, reading and writing to instance fields
// on MyState
}
}
...
var state = new MyState(/* additional values if needed */);
var result = ctx.Calculate(42, state.MyFunc);

最新更新