构建表达式树

我正在努力解决如何为更多lambda建立表达式树的想法,例如下面的那个,更不用说可能有多个语句的东西了。 例如:

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

我很感激任何想法。

我建议阅读Expression类的方法列表,列出所有选项,以及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>(body, pX); Func compiled = lambda.Compile();