【问题标题】:Building Expression Trees构建表达式树
【发布时间】:2011-06-08 03:09:20
【问题描述】:

我正在苦苦思索如何为更多 lambdas 构建表达式树,例如下面的那个,更不用说可能有多个语句的东西了。例如:

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

如果有任何想法,我将不胜感激。

【问题讨论】:

    标签: c# linq lambda expression-trees


    【解决方案1】:

    我建议阅读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();
    

    【讨论】:

    • 感谢您非常明确的回复...我已经阅读了一段时间,并且似乎在转圈,似乎总是缺少部分...
    • 小注:我的环境中不存在Expression.Member(...),所以需要改成Expression.Property(...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多