开发者

More on casting Func<T,T> and Expression<Func<T,T>>

开发者 https://www.devze.com 2022-12-16 11:06 出处:网络
I\'ve spent hours with this but haven\'t managed... Please see example below - How can this be done? The idea is to build a compiled expression of type Func<dynamic, dynamic> given an Expressi

I've spent hours with this but haven't managed...

Please see example below - How can this be done?

The idea is to build a compiled expression of type Func<dynamic, dynamic> given an Expression<Func<T1,T2>> passed by the class' consumer. I have been able to solve this problem (thanks to开发者_Python百科 SO) IF the types T1 and T2 are known at design time. But I'm looking for a solution for the case in which T1 and T2 are NOT known at design time.

Is this possible?

Thanks a lot!

public class ExpressionExample
{
    private Func<dynamic, dynamic> _compiledExpression;

    public ExpressionExample(LambdaExpression lambdaExpression)
    {
        // How does one get a compiled expression of type
        // Func<dynamic, dynamic> at this point given lambdaExpression?
    }
}


Unless I'm not understanding your question, this should work:

public class ExpressionExample<T1, T2>
{
    private Func<dynamic, dynamic> _compiledExpression;

    public ExpressionExample(
        Expression<Func<T1, T2>> lambdaExpression)
    {
        // How does one get a compiled expression of type
        // Func<dynamic, dynamic> at this point given lambdaExpression?
        var func = lambdaExpression.Compile();
        _compiledExpression = (dynamic x) => (dynamic)func((T1)x);
    }
}


You'll need to call Compile on the LambdaExpression, then build and compile another expression tree that calls the delegate using Expression.Invoke(Expression, params Expression).


I was looking in to something similar myself. Being a newbie I won't attempt to answer your question in full but maybe you can find the answer from the answer given to me from forums.asp.net which I also posted right here on stackoverflow.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号