如何将返回 Span 的方法作为参数传递?
using System.Memory;
public Span<byte> CallSpanFactory1(Func<Span<byte>> spanFactory)
{
return spanFactory();
}
Run Code Online (Sandbox Code Playgroud)
此代码返回错误“类型‘Span’不能用作类型参数”(这是有道理的,因为使用 ref 结构作为泛型类型参数可能会导致装箱,因此被禁止)。
我有一个这种形状的函数,可以进行一维求根:
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> …
是否可以将新的System.Memory Span结构与二维数据数组一起使用?
double[,] testMulti =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 9.5f, 10, 11 },
{ 12, 13, 14.3f, 15 }
};
double[] testArray = { 1, 2, 3, 4 };
string testString = "Hellow world";
testMulti.AsSpan(); // Compile error
testArray.AsSpan();
testString.AsSpan();
Run Code Online (Sandbox Code Playgroud)
尽管testArray和testString具有AsSpan扩展名,但testMulti不存在此类扩展名。
Span的设计是否仅限于处理一维数据数组?
我还没有找到使用Span处理testMulti数组的明显方法。
在哪里可以找到 Span<T> 和 Memory<T> 等内容的实际文档?