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

我想使用Linq表达式树来调用Span的索引器。 代码如下:

 var spanGetter = typeof(Span) .MakeGenericType(typeof(float)).GetMethod("get_Item"); var myFloatSpan = Expression.Parameter(typeof(Span), "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

我有一个解决方案,但它远非理想,你会看到。 我们重新使用C#语法糖引擎。

 class Program { static void Main(string[] args) { var spanGetter = typeof(Program).GetMethod("GetItem").MakeGenericMethod(typeof(float)); var myFloatSpan = Expression.Parameter(typeof(Span), "s"); var myValue = Expression.Call( null, spanGetter, myFloatSpan, Expression.Constant(42)); var myAdd = Expression.Add( myValue, Expression.Constant(13f)); var expr = Expression.Lambda(myAdd, myFloatSpan).Compile(); var span = new Span(new float[43]); span[42] = 12.3456f; Console.WriteLine(expr(span)); // -> 25.3456 } // hopefully, this shouldn't be too bad in terms of performance... // C# knows how to do compile this, while Linq Expressions doesn't public static T GetItem(Span span, int index) => span[index]; // we need that because we can't use a Span directly with Func // we could make it generic also I guess public delegate float MyFunc(Span span); }