c# - How can I get object instance from ()=>foo.Title expression -
i have simple class property
class foo { string title { get; set; } }
i trying simplify data binding calling function like
bindtotext(titletextbox, ()=>foo.title );
which declared like
void bindtotext<t>(control control, expression<func<t>> property) { var mex = property.body memberexpression; string name = mex.member.name; control.databindings.add("text", ??? , name); }
so put in ???
instance of foo
class. how refernce calling foo
instance lambda expression?
edit: instance should there somewhere because can call property.compile()
, create delegate uses foo
instance inside bindtotext
function. question if can done without adding reference instance in function parameters. call upon occum's razor yield simplest solution.
edit 2: many have failed notice closure exists in accessing instance of foo
inside function, if compile lambda. how come compiler knows find instance, , don't? insist there has answer, without having pass argument.
solution
thanks virtualblackfox solution such:
void bindtext<t>(textboxbase text, expression<func<t>> property) { var mex = property.body memberexpression; string name = mex.member.name; var fex = mex.expression memberexpression; var cex = fex.expression constantexpression; var fld = fex.member fieldinfo; var x = fld.getvalue(cex.value); text.databindings.add("text", x, name); }
which alows me type bindtext(titletext, () => foo.title);
.
small linqpad sample of want :
void foo<t>(expression<func<t>> prop) { var propertygetexpression = prop.body memberexpression; // display property accessing, here "height" propertygetexpression.member.name.dump(); // "s" replaced field access on compiler-generated class closure var fieldonclosureexpression = propertygetexpression.expression memberexpression; // find compiler-generated class var closureclassexpression = fieldonclosureexpression.expression constantexpression; var closureclassinstance = closureclassexpression.value; // find field value, in case it's reference "s" variable var closurefieldinfo = fieldonclosureexpression.member fieldinfo; var closurefieldvalue = closurefieldinfo.getvalue(closureclassinstance); closurefieldvalue.dump(); // know expression property access propertyinfo instance // , access value (yes compiling expression have been simpler :d) var propertyinfo = propertygetexpression.member propertyinfo; var propertyvalue = propertyinfo.getvalue(closurefieldvalue, null); propertyvalue.dump(); } void main() { string s = "hello world"; foo(() => s.length); }
Comments
Post a Comment