How to cast Expression> to Expression>

后端 未结 4 1826
借酒劲吻你
借酒劲吻你 2020-11-29 02:12

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

Expression>

to the type:

Exp         


        
4条回答
  •  温柔的废话
    2020-11-29 02:45

    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> AddBox
            (Expression> 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>
                 (converted, expression.Parameters);
        }
    
        // Just a simple demo
        static void Main()
        {
            Expression> x = text => DateTime.Now;
            var y = AddBox(x);        
            object dt = y.Compile()("hi");
            Console.WriteLine(dt);
        }        
    }
    

提交回复
热议问题