c# - How to set property value using Expressions? -


this question has answer here:

given following method:

public static void setpropertyvalue(object target, string propname, object value) {     var propinfo = target.gettype().getproperty(propname,                          bindingflags.instance | bindingflags.public | bindingflags.nonpublic | bindingflags.declaredonly);      if (propinfo == null)         throw new argumentoutofrangeexception("propname", "property not found on target");     else         propinfo.setvalue(target, value, null); } 

how go writing it's expression enabled equivalent without needing pass in parameter target?

why instead of setting property directly can hear say. example suppose have following class property has public getter private setter:

public class customer  {    public string title {get; private set;}    public string name {get; set;} } 

i able call:

var mycustomerinstance = new customer(); setpropertyvalue<customer>(cust => mycustomerinstance.title, "mr"); 

now here sample code.

public static void setpropertyvalue<t>(expression<func<t, object>> memberlamda , object value) {     memberexpression memberselectorexpression;     var selectorexpression = memberlamda.body;     var castexpression = selectorexpression unaryexpression;      if (castexpression != null)         memberselectorexpression = castexpression.operand memberexpression;     else         memberselectorexpression = memberlamda.body memberexpression;      // how value of mycustomerinstance can invoke setvalue passing in param? possible  } 

any pointers?

you cheat , make life easier extension method:

public static class lambdaextensions {     public static void setpropertyvalue<t, tvalue>(this t target, expression<func<t, tvalue>> memberlamda, tvalue value)     {         var memberselectorexpression = memberlamda.body memberexpression;         if (memberselectorexpression != null)         {             var property = memberselectorexpression.member propertyinfo;             if (property != null)             {                 property.setvalue(target, value, null);             }         }     } } 

and then:

var mycustomerinstance = new customer(); mycustomerinstance.setpropertyvalue(c => c.title, "mr"); 

the reason why easier because have target on extension method invoked. lambda expression simple member expression without closures. in original example target captured in closure , bit tricky underlying target , propertyinfo.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -