我可以将局部变量作为常量而不是闭包引用捕获到LINQ表达式中吗? [英] Can I capture a local variable into a LINQ Expression as a constant rather than a closure reference?

查看:66
本文介绍了我可以将局部变量作为常量而不是闭包引用捕获到LINQ表达式中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想说

int x = magic(), y = moremagic();
return i => i + (x/y);

,并将x捕获为常量而不是变量引用.这个想法是x永远不会改变,因此当以后编译表达式时,编译器可以进行常数折叠并产生更有效的代码-即通过指针取消引用到闭合记录来计算x/y一次,而不是每次调用时.

and have the x be captured as a constant instead of a variable reference. The idea is that x will never change and so when the expression is later compiled, the compiler to can do constant folding and produce more efficient code -- i.e. calculating x/y once instead of on every call, via pointer dereferences into a closure record.

无法在方法中将x标记为只读,并且编译器不够聪明,无法检测到创建表达式后它不会更改.

There is no way to mark x as readonly within a method, and the compiler is not clever enough to detect that it doesn't change after the creation of the expression.

我讨厌必须手动构建表达式.有什么好主意吗?

I'd hate to have to build the expression by hand. Any brilliant ideas?

更新:我最终使用了奇妙的 LinqKit 建立一个部分评估程序,它将执行我想要的替换.仅当您知道相关参考不会更改,该转换才是安全的,但它对于我而言是有效的.通过在其中添加一两个额外的检查,可以将部分评估仅限制于您控制的直接闭合成员,这在检查LinqKit中提供的示例代码时非常明显.

UPDATE: I ended up using the marvelous LinqKit to build a partial evaluator that will do the substitutions I want. The transform is only safe if you know that relevant references will not change, but it worked for my purposes. It is possible to restrict the partial evaluation only to direct members of your closure, which you control, by adding an extra check or two in there, which is fairly obvious on inspection of the sample code provided in the LinqKit.

/// <summary>Walks your expression and eagerly evaluates property/field members and substitutes them with constants.
/// You must be sure this is semantically correct, by ensuring those fields (e.g. references to captured variables in your closure)
/// will never change, but it allows the expression to be compiled more efficiently by turning constant numbers into true constants, 
/// which the compiler can fold.</summary>
public class PartiallyEvaluateMemberExpressionsVisitor : ExpressionVisitor
{
    protected override Expression VisitMemberAccess(MemberExpression m)
    {
        Expression exp = this.Visit(m.Expression);

        if (exp == null || exp is ConstantExpression) // null=static member
        {
            object @object = exp == null ? null : ((ConstantExpression)exp).Value;
            object value = null; Type type = null;
            if (m.Member is FieldInfo)
            {
                FieldInfo fi = (FieldInfo)m.Member;
                value = fi.GetValue(@object);
                type = fi.FieldType;
            }
            else if (m.Member is PropertyInfo)
            {
                PropertyInfo pi = (PropertyInfo)m.Member;
                if (pi.GetIndexParameters().Length != 0)
                    throw new ArgumentException("cannot eliminate closure references to indexed properties");
                value = pi.GetValue(@object, null);
                type = pi.PropertyType;
            }
            return Expression.Constant(value, type);
        }
        else // otherwise just pass it through
        {
            return Expression.MakeMemberAccess(exp, m.Member);
        }
    }
}

推荐答案

在C#中无法做到这一点.编译器不支持按值/常量捕获变量.也不能以这种方式在运行时将非const值转换为const值.

No there is no way to do this in C#. The compiler does not support capturing variables by value / const. Nor can you convert a non-const value into a const value at runtime in this manner.

此外,C#编译器仅在初始编译期间对已知常量值进行常量折叠.如果可以在运行时将值冻结为常量,则不会参与编译器常量折叠,因为它在运行时发生.

Additionally the C# compiler only does constant folding during the initial compilation for known constant values. If it was possible to freeze a value at runtime into a constant it wouldn't participate in compiler constant folding because it happens at runtime.

这篇关于我可以将局部变量作为常量而不是闭包引用捕获到LINQ表达式中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆