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

标签 c# linq expression-trees

我想使用 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& (又名 ref struct )而不是类型 Single (又名 struct)。

如何评估 Span<T>来自表达式树?

最佳答案

我有一个解决方案,但它远非理想,如您所见。我们重新使用 C# 语法糖引擎。

class Program
{
    static void Main(string[] args)
    {
        var spanGetter = typeof(Program).GetMethod("GetItem").MakeGenericMethod(typeof(float));

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

        var myValue = Expression.Call(
            null,
            spanGetter,
            myFloatSpan,
            Expression.Constant(42));

        var myAdd = Expression.Add(
            myValue,
            Expression.Constant(13f));

        var expr = Expression.Lambda<MyFunc>(myAdd, myFloatSpan).Compile();

        var span = new Span<float>(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<T>(Span<T> span, int index) => span[index];

    // we need that because we can't use a Span<T> directly with Func<T>
    // we could make it generic also I guess
    public delegate float MyFunc(Span<float> span);
}

关于c# - 如何使用 Linq 表达式树从 Span<T> 中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112628/

相关文章:

c# - 只需一键即可做出两个决定

c# - 在异步调用中处理异常的最佳实践

c# - selenium webdriver 单击 javascript 链接

c# - Entity Framework - 保存父实体时未将新子实体添加到数据库(仅在生产环境中)

.net - 如何指定要从表达式树方法返回的对象?

c# - 如何发送延续 token 来查询azure时间序列见解?

c# - PagedList与ViewModels和.Skip()。Take()一起使用

c# - ASP.NET 中的 Gridview 排序

c# - Expression<Func<in T, bool>> 或 Expression<Func<TBase,bool>> 到 Expression<Func<T,bool>> 转换器

sql - 在运行时将 SQL 转换为 Linq To Objects 表达式