c# - Expression Trees with dynamic parameter -
i want convert this:
func<dynamic, object> myfunc = t => return t.name + " " + t.surname;
into expression tree.
what have came with, this:
parameterexpression target = expressionparameter(typeof(dynamic), "target"); parameterexpression result = expressionparameter(typeof(object), "result"); blockexpression block = expression.block( new [] { result }, expression.assign( result, expression.add( expression.add( expression.property(target, "name"), expression.constant(" ", typeof(string)) ), expression.property(target, "surname") ) ) ); func<dynamic, object> myfunc = expression.lambda<dynamic, object>>(block, target).compile();
however, compiler doesn't typeof(dynamic)
, , kind of it. dynamic
isn't type, object
in essence.
so proceeded change parameterexpression
:
parameterexpression target = expressionparameter(typeof(object), "target");
the code compiles, there problem @ runtime.
i trying value of property name
of target
, may have sense if object dynamic
.
but since target
considered of type object
, expression throws error telling me name
doesn't exist property.
is there expression fetching dynamic property?
for or interested in solution:
parameterexpression target = expression.parameter(typeof(object), "target"); parameterexpression result = expression.parameter(typeof(object), "result"); callsitebinder getname = binder.getmember( csharpbinderflags.none, "name", typeof(program), new csharpargumentinfo[] { csharpargumentinfo.create(csharpargumentinfoflags.none, null) } ); callsitebinder getsurname= binder.getmember( csharpbinderflags.none, "surname", typeof(program), new csharpargumentinfo[] { csharpargumentinfo.create(csharpargumentinfoflags.none, null) } ); blockexpression block = expression.block( new[] { result }, expression.assign( result, expression.call(typeof(string).getmethod("concat", new type[] { typeof(object[]) }), expression.newarrayinit(typeof(object), expression.dynamic(getname, typeof(object), target), expression.constant(" ", typeof(object)), expression.dynamic(getsurname, typeof(object), target) ) ) ) ); func<dynamic, object> myfunc = expression.lambda<func<dynamic, object>>(block, target).compile();
here's doing:
- created
callsitebinder
obtains value of dynamic propertyname
of dynamic object passed argument - created
callsitebinder
obtains value of dynamic propertysurname
of dynamic object passed argument - invoked method
string.concat(params object[] args)
. that, need send arguments array ofobject
. i'm creating array values ofgetname
," "
, ,getsurname
.
i used following answer guide , reference:
c# 4 “dynamic” in expression trees
with above approach, 1 this:
dynamic person = new expandoobject(); person.name = "matt"; person.surname = "smith"; object value = myfunc(person); console.writeline(value); //will print out "matt smith" //internally calls: //string.concat(new object[] { person.name, " ", person.surname });
Comments
Post a Comment