c# - How to Set a property using a func<> -


say have function how set property on record

public void setproperty<trecord, tenum>(trecord item,                                           func<trecord, tenum> property, string enumvalue )    tenum : struct    trecord : class {      tenum enumtype;      if (enum.tryparse(enumvalue, true, out enumtype))      {          //how set this?          property.invoke(item) = enumtype;      } } 

i'd prefer not switch expression. know how set property?

public void setproperty<trecord, tenum>(trecord item,                                 action<trecord, tenum> property, string enumvalue)     tenum : struct     trecord : class {     tenum enumtype;     if (enum.tryparse(enumvalue, true, out enumtype))     {         property(item, enumtype);     } } 

better way...

public tenum? asenum<tenum>(string enumvalue)     tenum : struct {     tenum enumtype;     if (enum.tryparse(enumvalue, true, out enumtype))     {         return enumtype;     }     return default(tenum); } 

usage examples...

myobj.prop = asenum<myenum>("value") ?? myenum.default; //versus  setpropery<myobject, myenum>(myobj, (r, e) => r.prop = e, "value"); 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -