我有一个这种形状的函数,可以进行一维求根:
public delegate double Fun(double x, object o);
public static void Solve(Fun f, out double y, object o)
{
y = f(1.0, o); // all the irrelevant details of the algorithm omitted
}
Run Code Online (Sandbox Code Playgroud)
这是一个固定的形状,以便使算法可重用。将此视为我无法更改的固定库函数(或者至少需要保持通用性和可重用性,并且不会针对此问题的具体情况进行更改)。
我想传递一个函数,该函数需要Span<T>保存在堆栈上的外部参数以避免分配,但显然不能将Span<T>其推入对象,因为这需要装箱和拆箱。
使用 lambda 表达式,调用代码可能类似于:
void CallingMethod()
{
Span<double> k1 = stackalloc double[n];
double answer;
Solve((x, o) => Wrapper(x, k1, o), out answer, null);
}
double Wrapper(double x, ReadOnlySpan<double> k1, object o)
{
return <some function of x and k1>;
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为您无法Span<T> …