c# - 从现有表达式创建新表达式

标签 c# .net lambda expression-trees expression

我有一个 Expression<Func<T,DateTime>>我想获取表达式的 DateTime 部分并从中提取月份。所以我会把它变成一个 Expression<Func<T,int>>我不太确定该怎么做。我看着 ExpressionTree Visitor但我无法让它像我需要的那样工作。这是 DateTime 表达式的示例

DateTimeExpression http://img442.imageshack.us/img442/6545/datetimeexpression.png

这是我想要创建的示例 MonthExpression http://img203.imageshack.us/img203/8013/datetimemonthexpression.png

看起来我需要创建一个新的 MemberExpression,它由 DateTime 表达式的 Month 属性组成,但我不确定。

最佳答案

是的,这正是您想要的 - 使用 Expression.Property是最简单的方法:

Expression func = Expression.Property(existingFunc.Body, "Month");
Expression<Func<T, int>> lambda = 
    Expression.Lambda<Func<T, int>>(func, existingFunc.Parameters);

我相信这应该没问题。它适用于这个简单的测试:

using System;
using System.Linq.Expressions;

class Person
{
    public DateTime Birthday { get; set; }
}

class Test
{
    static void Main()
    {
        Person jon = new Person 
        { 
            Birthday = new DateTime(1976, 6, 19)
        };

        Expression<Func<Person,DateTime>> dateTimeExtract = p => p.Birthday;
        var monthExtract = ExtractMonth(dateTimeExtract);
        var compiled = monthExtract.Compile();
        Console.WriteLine(compiled(jon));
    }

    static Expression<Func<T,int>> ExtractMonth<T>
        (Expression<Func<T,DateTime>> existingFunc)
    {
        Expression func = Expression.Property(existingFunc.Body, "Month");
        Expression<Func<T, int>> lambda = 
            Expression.Lambda<Func<T, int>>(func, existingFunc.Parameters);
        return lambda;
    }                                        
}

关于c# - 从现有表达式创建新表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2377452/

相关文章:

c# - XML 文档 SelectSingleNode 返回 null

lambda - Java 8 currying 函数,无法确定 int[] 返回类型

c# - 为什么 DateTime.Parse 这么慢?

.net - 在 F# 中编码(marshal)具有 `char` 数组字段的结构数组

java - JRE 如何为具有非有效最终局部变量的 lambda 体创建并发问题?

c# - 为什么我不能使用这个嵌套的 lambda 表达式?

c# - 如何通过代码优先全局更改小数点的精度和小数位?

c# - 在 Web 浏览器中运行 WPF 浏览器应用程序

c# - : caching through HttpContext. Current.Cache 或静态缓存哪个更好?

.net - 是否可以将 dll 转换为源代码?