1

如果我想从控制台获取用户输入到我的表达式树。最好的方法是什么?以及如何使变量“名称”鸭子打字?

这是我的代码。

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

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

            // Output
            MethodInfo Write = typeof(System.Console).GetMethod("Write", new Type[] { typeof(string) });
            ConstantExpression param = Expression.Constant("What is your name? ", typeof(string));
            Expression output = Expression.Call(null, Write, param);
            statements.Add(output);

            // Input
            MethodInfo ReadLine = typeof(System.Console).GetMethod("ReadLine");
            ParameterExpression exprName = Expression.Variable(typeof(String), "name");
            Expression exprReadLine = Expression.Call(null, ReadLine);

            // .NET 4.0 (DlR 0.9) from Microsoft.Scripting.Core.dll
            // Expression.Assign and Expression.Scope
            ScopeExpression input = Expression.Scope(Expression.Assign(exprName, exprReadLine), exprName);
            statements.Add(input);

            // Create the lambda
            LambdaExpression lambda = Expression.Lambda(Expression.Block(statements));

            // Compile and execute the lambda
            lambda.Compile().DynamicInvoke();

            Console.ReadLine();
        }
    }
}
4

1 回答 1

1

表达式树旨在执行固定操作 - 特别是,成员访问MemberInfo在表达式树创建时需要一个已知的(等)(因为它们是不可变的)。

如果您使用的是 4.0,则可以复制生成的代码dynamic,但老实说,这种情况下更好的方法很简单:不要使用表达式树。

对于这种对成员的动态访问,反射或ComponentModel( ) 都是理想的选择。TypeDescriptor

另外 - 调用Compile你只使用一次的东西不会节省任何时间,使用DynamicInvoke也不是......你需要使用类型化的委托表单(Invoke)。

于 2009-01-21T20:40:46.680 回答