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 propertyinfos 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

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -