构建表达式树

Cra*_*g D 6 c# linq lambda expression-trees

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

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

我很感激任何想法.

use*_*116 5

我建议阅读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<Func<double?,byte[]>>(body, pX);

Func<double?,byte[]> compiled = lambda.Compile();
Run Code Online (Sandbox Code Playgroud)