本文介绍了如何转换 Expression<Func<T, DateTime>>到表达式&lt;Func&lt;T,对象&gt;&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索,但我找不到如何从类型转换

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 ;)

推荐答案

你不能只是在它们之间转换,因为它们不是同一种东西.但是,您可以在表达式树中有效地添加转换:

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);
    }
}

这篇关于如何转换 Expression<Func<T, DateTime>>到表达式&lt;Func&lt;T,对象&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:43