2011-06-08 127 views
6

我正在为如何为更多lambda表达式构建表达式树(比如下面的表达式)而烦恼,更不用说可能有多个语句的东西了。例如:构建表达式树

Func<double?, byte[]> GetBytes 
     = x => x.HasValue ? BitConverter.GetBytes(x.Value) : new byte[1] { 0xFF }; 

我将不胜感激。

回答

5

我建议通过list of methods on the Expression class阅读,所有的选项都列在那里,并Expression Trees Programming Guide

至于此特定实例:

/* build our parameters */ 
var pX = Expression.Parameter(typeof(double?)); 

/* build the body */ 
var body = Expression.Condition(
    /* condition */ 
    Expression.Property(pX, "HasValue"), 
    /* if-true */ 
    Expression.Call(typeof(BitConverter), 
        "GetBytes", 
        null, /* no generic type arguments */ 
        Expression.Member(pX, "Value")), 
    /* if-false */ 
    Expression.Constant(new byte[] { 0xFF }) 
); 

/* build the method */ 
var lambda = Expression.Lambda<Func<double?,byte[]>>(body, pX); 

Func<double?,byte[]> compiled = lambda.Compile(); 
+0

感谢非常明确回应......我一直在阅读有关这一段时间,似乎在兜兜转转,有似乎总是缺件... – 2011-06-08 06:14:33

+0

小记:Expression.Member(...)在我的环境中不存在,所以需要将其更改为Expression.Property(...) – 2011-06-08 06:24:38

+0

@Craig:你是对的,我的意思也是属性。 – user7116 2011-06-08 11:39:19