c# - How to create an Expression<Func<dynamic, dynamic>> - Or is it a bug? -
during work expression trees few days now, came across find difficult understand; able shed light here.
if code expression<func<dynamic, dynamic>> expr1 = x => 2 * x;
compiler complain , won't anywhere. however, seems if create 1 such expression through method compiler seems happy , resulting app works. doesn't make sense, i'm wondering goes on behind curtains.
i suppose that, under hood, expression returned convertexpression
perhaps of type expression<func<object, object>>
, valid type, puzzles me can't use expression<func<dynamic, dynamic>>
type in declaration , yet can use return type of method. see example below.
thanks lot!
public class expressionexample { public void main() { // doesn't compile: //expression<func<dynamic, dynamic>> expr1 = x => 2 * x; // compiles , works - ok expression<func<double, double>> expr2 = x => 2 * x; func<double, double> func2 = (func<double, double>)expr2.compile(); console.writeline(func2(5.0).tostring()); // outputs 10 // compiles , works - ??? confusing block... expression<func<dynamic, dynamic>> expr3 = convertexpression(expr2); func<dynamic, dynamic> func3 = (func<dynamic, dynamic>)expr3.compile(); console.writeline(func3(5.0).tostring()); // outputs 10 // side note: compiles , works: expression<func<object, object>> expr4 = x => double.parse(2.tostring()) * double.parse(x.tostring()); func<object, object> func4 = (func<object, object>)expr4.compile(); console.writeline(func4(5.0).tostring()); // outputs 10 } private expression<func<dynamic, dynamic>> convertexpression<tinput, toutput>(expression<func<tinput, toutput>> expression) { expression<func<object, tinput>> converttoinput = value => (tinput)value; // following doesn't compile: var input = expression.parameter(typeof(dynamic), "input"); var input = expression.parameter(typeof(object), "input"); expression<func<toutput, dynamic>> converttooutput = value => (dynamic)value; var body = expression.invoke(converttooutput, expression.invoke(expression, expression.invoke(converttoinput, input))); var lambda = expression.lambda<func<dynamic, dynamic>>(body, input); return lambda; } }
i suppose that, under hood, expression returned convertexpression perhaps of type
expression<func<object, object>>
, valid type
correct.
i can't use
expression<func<dynamic, dynamic>>
type in declaration , yet can use return type of method.
this portion of statement incorrect. note in example, legal use type in declaration of local variable.
the bit not legal execution of dynamic operation inside lambda being converted expression tree type. specific expression tree type irrelevant; matters operation dynamic.
Comments
Post a Comment