c# - Use value of property expression inside expression tree -
consider property expression t => t.myproperty
t
of type myclass
. how can use property expression inside new expression perform method call?
pure c#
:
class myclass { public string myproperty { get; set; } } static void foo(string foo) { } lambdaexpression getexpression(expression<func<myclass, object>> expr) { return expr; } var myclass = new myclass(); foo(myclass.myproperty);
now expressions...?
var expr = getexpression(m => m.myproperty); var mi = typeof(program).getmethod(nameof(program.foo), bindingflags.public | bindingflags.static); var myclass = new myclass(); // what?? // var call = expression.call(mi, ???expr??); // var invoke = expression.invoke(call, fooparameter);
i want use result of expr
, use in call foo
. know can in 2 steps, call expr.compile().dynamicinvoke(myclass)
value, not i'm asking here.
i want build expression takes property getter expression , performs call foo(
result of expression)
. cannot figure out how use expression parameter method call.
there's 2 ways of doing this, depending on complexity. in case, can re-use parameter inner expression - bubbling outwards; discarding our old lambda, using .body
, .parameters
. example:
var call = expression.lambda<action<myclass>>( expression.call(mi, expr.body), expr.parameters); var myclass = new myclass { myproperty = "yay!" }; call.compile().invoke(myclass);
the other way use invoke
on inner lambda:
var outerparameter = expression.parameter(typeof(myclass)); var typed = expression.convert(expression.invoke(expr, outerparameter), typeof(string)); var call = expression.lambda<action<myclass>>(expression.call(mi, typed), outerparameter);
the second form (invoke
) useful when can't conveniently control parameters in 2 places - or where, example, have multiple inner expressions different parameter instances.
Comments
Post a Comment