c# - How can I pass a list of properties to a method using lambda expressions -
let's have method, prints names , values of properties of object:
public void printproperties(object o, params string[] propertynames) { foreach (var propertyname in propertynames) { // property info, // property's value, // print property-name , -value } } // method can used printproperties(user, "firstname", "lastname", "email");
now instead of having pass list of strings method, i'd change method properties can specified using lambda expressions (not sure if that's correct term).
e.g. i'd able call method (somehow) this:
printproperties(user, u->u.firstname, u->u.lastname, u->u.email);
the goal is, give user of method intellisense support, prevent typing errors. (similar asp.net mvc helper methods, textboxfor(u=>u.name)
).
how have define method, , how can propertyinfo
s inside method?
use declaration this:
void printproperties<t>(t obj, params expression<func<t, object>>[] propertyselectors) { ... }
callable like:
printproperties(user, u => u.firstname, u => u.lastname, u => u.email);
as getting property-names out each lambda, see retrieving property name lambda expression. note have may have go little bit deeper provided in answer in case property value-type int
(in case, compiler generate unary convert
expression on member-access want, in order box struct).
Comments
Post a Comment