How do I specify the object to return from an expression tree method?

前端 未结 1 1946
礼貌的吻别
礼貌的吻别 2021-02-12 07:57

I\'m trying to create a method using an expression tree that returns an object, but I can\'t figure out how to actually specify the object to return. I\'ve tried reading this, b

相关标签:
1条回答
  • 2021-02-12 08:35

    Apparently a return is a GotoExpression that you can create with the Expression.Return factory method. You need to create a label at the end to jump to it. Something like this:

    // an expression representing the obj variable
    ParameterExpression objExpression = ...;
    
    LabelTarget returnTarget = Expression.Label(typeof(StructType));
    
    GotoExpression returnExpression = Expression.Return(returnTarget, 
        objExpression, typeof(StructType));
    
    LabelExpression returnLabel = Expression.Label(returnTarget, defaultValue);
    
    BlockExpression block = Expression.Block(
        /* ... variables, all the other lines and... */,
        returnExpression,
        returnLabel);
    

    The types of the label target and the goto expression must match. Because the label target has a type, the label expression must have a default value.

    0 讨论(0)
提交回复
热议问题