如何投放前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);
}
}