加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:35:17 所属栏目:百科 来源:网络整理
导读:我有一个表达式 Func T,DateTime我想取表达式的DateTime部分并从中拉出Month.所以我会把它变成一个表达式 Func T,int我真的不确定怎么做.我看了 ExpressionTree Visitor,但我不能像我需要的那样工作.以下是DateTime表达式的示例 DateTimeExpression http://i
我有一个表达式< Func< T,DateTime>>我想取表达式的DateTime部分并从中拉出Month.所以我会把它变成一个表达式< 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,existingFunc.Parameters);
        return lambda;
    }                                        
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读