在.NET 3.5表达式树中的赋值

12

能否将赋值操作编码到表达式树中?

5个回答

12

您可以使用.NET 4.0库来实现它。通过将Microsoft.Scripting.Core.dll导入到您的.NET 3.5项目中。

我正在使用DLR 0.9 - 在版本1.0中,Expression.Block和Expression.Scope可能会有一些变化(您可以从http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234查看参考)。

以下示例是为了向您展示。

using System;
using System.Collections.Generic;
using Microsoft.Scripting.Ast;
using Microsoft.Linq.Expressions;
using System.Reflection;

namespace dlr_sample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Expression> statements = new List<Expression>();

            ParameterExpression x = Expression.Variable(typeof(int), "r");
            ParameterExpression y = Expression.Variable(typeof(int), "y");

            statements.Add(
                Expression.Assign(
                    x,
                    Expression.Constant(1)
                )
             );

            statements.Add(
                Expression.Assign(
                    y,
                    x
                )
             );

            MethodInfo cw = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) });

            statements.Add(
                Expression.Call(
                    cw,
                    y
                )
            );

            LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));

            lambda.Compile().DynamicInvoke();
            Console.ReadLine();
        }
    }
}

12

不,我认为不是这样的。

当转换Lambda表达式时,C#编译器肯定会禁止它:

int x;
Expression<Func<int,int>> foo = (x=y); // Assign to x and return value

这会导致错误:

CS0832: An expression tree may not contain an assignment operator

5

我为此编写了一个扩展方法:

/// <summary>
/// Provides extensions for converting lambda functions into assignment actions
/// </summary>
public static class ExpressionExtenstions
{
    /// <summary>
    /// Converts a field/property retrieve expression into a field/property assign expression
    /// </summary>
    /// <typeparam name="TInstance">The type of the instance.</typeparam>
    /// <typeparam name="TProp">The type of the prop.</typeparam>
    /// <param name="fieldGetter">The field getter.</param>
    /// <returns></returns>
    public static Expression<Action<TInstance, TProp>> ToFieldAssignExpression<TInstance, TProp>
        (
        this Expression<Func<TInstance, TProp>> fieldGetter
        )
    {
        if (fieldGetter == null)
            throw new ArgumentNullException("fieldGetter");

        if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))
            throw new ArgumentException(
                @"Input expression must be a single parameter field getter, e.g. g => g._fieldToSet  or function(g) g._fieldToSet");

        var parms = new[]
                        {
                            fieldGetter.Parameters[0],
                            Expression.Parameter(typeof (TProp), "value")
                        };

        Expression body = Expression.Call(AssignmentHelper<TProp>.MethodInfoSetValue,
                                          new[] {fieldGetter.Body, parms[1]});

        return Expression.Lambda<Action<TInstance, TProp>>(body, parms);
    }


    public static Action<TInstance, TProp> ToFieldAssignment<TInstance, TProp>
        (
        this Expression<Func<TInstance, TProp>> fieldGetter
        )
    {
        return fieldGetter.ToFieldAssignExpression().Compile();
    }

    #region Nested type: AssignmentHelper

    private class AssignmentHelper<T>
    {
        internal static readonly MethodInfo MethodInfoSetValue =
            typeof (AssignmentHelper<T>).GetMethod("SetValue", BindingFlags.NonPublic | BindingFlags.Static);

        private static void SetValue(ref T target, T value)
        {
            target = value;
        }
    }

    #endregion
}

我似乎无法让它正常工作,是否有修订版或博客文章可以参考? - Maslow

4

正如Jon Skeet和TraumaPony已经说过的,Expression.Assign在.NET 4之前是不可用的。以下是另一个具体示例,说明如何解决这个缺失的问题:

public static class AssignmentExpression
{
    public static Expression Create(Expression left, Expression right)
    {
        return
            Expression.Call(
               null,
               typeof(AssignmentExpression)
                  .GetMethod("AssignTo", BindingFlags.NonPublic | BindingFlags.Static)
                  .MakeGenericMethod(left.Type),
               left,
               right);
    }

    private static void AssignTo<T>(ref T left, T right)  // note the 'ref', which is
    {                                                     // important when assigning
        left = right;                                     // to value types!
    }
}

那么只需在Expression.Assign()的位置调用AssignmentExpression.Create()即可。

2

您可以通过嵌套表达式树来解决这个问题。调用一个lambda函数,其中一个参数是被赋值变量的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接