2009-01-21 2 views
1

콘솔에서 내 Expression Tree로 사용자 입력을 받고 싶습니다. 가장 좋은 방법은 무엇입니까? 변수 '이름'을 입력하는 방법은 무엇입니까?Expression Tree를 사용하여 ReadLine을 만드는 가장 좋은 방법은 무엇입니까?

내 코드는 다음과 같습니다.

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(); 
     } 
    } 
} 

답변

1

식 트리가 고정 된 작업을 수행하도록 설계 - 특히, 멤버 액세스를 원하는 것입니다 알려진 식 트리 창조의 시점에서 MemberInfo (등) (그들은 불변이기 때문에).

4.0을 가지고 놀고 있다면 generated code from dynamic을 복제 할 수 있지만 솔직히이 시나리오에서 더 좋은 방법은 간단히 표현 트리를 사용하지 않는 것입니다.

반영 또는 ComponentModel (TypeDescriptor)은 회원에 대한이 동적 액세스에 이상적입니다.

또한 한 번만 사용하는 항목에 Compile을 호출하면 아무런 시간도 저장되지 않으며 DynamicInvoke을 사용하면 입력 된 위임 양식 (Invoke)을 사용해야합니다.

+0

@MarkGravell : 표현식 트리와 동적 유형에 대한 귀하의 답을 찾았으며 매우 도움이되었습니다. 고맙습니다! 그러나 나는 [이 문제] (http://stackoverflow.com/q/24939618/938668)에서 곤란을 겪고있다. 당신이 볼 기회를 얻으면, 나는 그것에 대한 당신의 생각에 감사 할 것입니다. –

관련 문제