c# - Get the name of a field from a class without an instance -
so use following utility name of field/property instance of class...
public static string fieldname<t>(expression<func<t>> source) { return ((memberexpression)source.body).member.name; } this allows me following:
public class coolcat { public string karatepower; } public class program { public static main() { public coolcat jimmy = new coolcat(); string jimmyskaratepowerfield = fieldname(() => jimmy.karatepower); } } this great serialization , other times when need string representation of field name.
but now, want able field name without having instance of class - instance, if setting table , want dynamically link fieldnames of columns actual fields in class (so refactorings, etc. not break it).
basically, feel don't quite syntax of how accomplish this, imagine this:
public static string classfieldname<t>(func<t> propertyfunction) { // field name? i'm not sure whether 'func' right thing here - imagine pass in lambda type expression or of sort? } public class program { public static main() { string catspowerfieldname = classfieldname<coolcat>((x) => x.karatepower); // 'catspowerfieldname' set "karatepower". } } i hope makes sense - i'm not vocab around subject know question little vague.
i have 2 methods use this.
the first extension method can used on object.
public static string getpropertyname<tentity, tproperty>(this tentity entity, expression<func<tentity, tproperty>> propertyexpression) { return propertyexpression.propertyname(); } which used like
public coolcat jimmy = new coolcat(); string jimmyskaratepowerfield = jimmy.getpropertyname(j => j.karatepower); the second use when don't have object.
public static string propertyname<t>(this expression<func<t, object>> propertyexpression) { memberexpression mbody = propertyexpression.body memberexpression; if (mbody == null) { //this handle nullable<t> properties. unaryexpression ubody = propertyexpression.body unaryexpression; if (ubody != null) { mbody = ubody.operand memberexpression; } if (mbody == null) { throw new argumentexception("expression not memberexpression", "propertyexpression"); } } return mbody.member.name; } this can used so
string karatepowerfield = extensions.propertyname<coolcat>(j => j.karatepower);
Comments
Post a Comment