如何投放前pression<&Func键LT; T,日期时间>>到防爆pression<&Func键LT; T,对象>> [英] How to cast Expression<Func<T, DateTime>> to Expression<Func<T, object>>

查看:162
本文介绍了如何投放前pression<&Func键LT; T,日期时间>>到防爆pression<&Func键LT; T,对象>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找,但我无法找到如何从类型转换

I've been searching but I can't find how to cast from the type

Expression<Func<T, DateTime>>

要的类型:

Expression<Func<T, object>>

所以,我必须再次到如此巨大的知识转动;)

So I must turn again to the SO vast knowledge ;)

推荐答案

您不能只是投他们之间,因为他们是不是同一种东西。但是,可以有效地恩pression树中添加一个转换:

You can't just cast between them, as they're not the same kind of thing. However, you can effectively add a conversion within the expression tree:

using System;
using System.Linq.Expressions;

class Test
{
    // This is the method you want, I think
    static Expression<Func<TInput,object>> AddBox<TInput, TOutput>
        (Expression<Func<TInput, TOutput>> expression)
    {
        // Add the boxing operation, but get a weakly typed expression
        Expression converted = Expression.Convert
             (expression.Body, typeof(object));
        // Use Expression.Lambda to get back to strong typing
        return Expression.Lambda<Func<TInput,object>>
             (converted, expression.Parameters);
    }

    // Just a simple demo
    static void Main()
    {
        Expression<Func<string, DateTime>> x = text => DateTime.Now;
        var y = AddBox(x);        
        object dt = y.Compile()("hi");
        Console.WriteLine(dt);
    }        
}

这篇关于如何投放前pression&LT;&Func键LT; T,日期时间&GT;&GT;到防爆pression&LT;&Func键LT; T,对象&gt;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆