如何使用 Linq 表达式树从 Span<T> 中获取值?

我想使用 Linq 表达式树来调用Span<T>. 代码如下:


var spanGetter = typeof(Span<>)

    .MakeGenericType(typeof(float)).GetMethod("get_Item");


var myFloatSpan = Expression.Parameter(typeof(Span<float>), "s");


var myValue = Expression.Call(

    myFloatSpan,

    spanGetter,

    Expression.Constant(42));


var myAdd = Expression.Add(

    myValue,

    Expression.Constant(13f));    

然而,这段代码失败了,因为myValue是类型Single&(aka ref struct)而不是类型Single(aka struct)。


如何Span<T>从表达式树评估 a ?


慕运维8079593
浏览 152回答 1
1回答

眼眸繁星

我有一个解决方案,但正如您将看到的,它远非理想。我们重用了 C# 语法糖引擎。class Program{&nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var spanGetter = typeof(Program).GetMethod("GetItem").MakeGenericMethod(typeof(float));&nbsp; &nbsp; &nbsp; &nbsp; var myFloatSpan = Expression.Parameter(typeof(Span<float>), "s");&nbsp; &nbsp; &nbsp; &nbsp; var myValue = Expression.Call(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; spanGetter,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myFloatSpan,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Expression.Constant(42));&nbsp; &nbsp; &nbsp; &nbsp; var myAdd = Expression.Add(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myValue,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Expression.Constant(13f));&nbsp; &nbsp; &nbsp; &nbsp; var expr = Expression.Lambda<MyFunc>(myAdd, myFloatSpan).Compile();&nbsp; &nbsp; &nbsp; &nbsp; var span = new Span<float>(new float[43]);&nbsp; &nbsp; &nbsp; &nbsp; span[42] = 12.3456f;&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(expr(span)); // -> 25.3456&nbsp; &nbsp; }&nbsp; &nbsp; // hopefully, this shouldn't be too bad in terms of performance...&nbsp; &nbsp; // C# knows how to do compile this, while Linq Expressions doesn't&nbsp; &nbsp; public static T GetItem<T>(Span<T> span, int index) => span[index];&nbsp; &nbsp; // we need that because we can't use a Span<T> directly with Func<T>&nbsp; &nbsp; // we could make it generic also I guess&nbsp; &nbsp; public delegate float MyFunc(Span<float> span);}
打开App,查看更多内容
随时随地看视频慕课网APP