Building Expression Trees

﹥>﹥吖頭↗ 提交于 2019-12-09 18:16:45

问题


I'm struggling with the idea of how to build an expression tree for more lambdas such as the one below, let alone something that might have multiple statements. For example:

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

I would appreciate any thoughts.


回答1:


I would suggest reading through the list of methods on the Expression class, all of your options are listed there, and the Expression Trees Programming Guide.

As for this particular instance:

/* 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();


来源:https://stackoverflow.com/questions/6273788/building-expression-trees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!