c# - Expression tree create dictionary with property values for class -


essentially i'm trying using expression trees

var properties = new dictionary<string, object>();  foreach (var propinfo in objtype.gettypeinfo().getproperties(bindingflags.public)) {     var name = propinfo.name;     var value = propinfo.getvalue(objinstance);      properties.add(name, value); }  return properties; 

i.e. create dictionary of name , value pairs name name of property objtype , value value of property instance objinstance of objtype

now converting expression should compile delegate does

func<t, dictionary<string, object>> func = => {     var properties = new dictionary<string, object>();      properties.add("prop1", (object)i.prop1);     properties.add("prop2", (object)i.prop2);     properties.add("prop3", (object)i.prop3);     // depending upon number of properties of t, add continue      return properties; }; 

i know how perform of this, not sure on how create local instance of dictionary , use (and return it) in subsequent expressions?

it should (comments inline):

public static func<t, dictionary<string, object>> getvaluesfunc<t>() {     type objtype = typeof(t);      var dict = expression.variable(typeof(dictionary<string, object>));     var par = expression.parameter(typeof(t), "obj");      var add = typeof(dictionary<string, object>).getmethod("add", bindingflags.public | bindingflags.instance, null, new[] { typeof(string), typeof(object) }, null);      var body = new list<expression>();     body.add(expression.assign(dict, expression.new(typeof(dictionary<string, object>))));      var properties = objtype.gettypeinfo().getproperties(bindingflags.public | bindingflags.instance);      (int = 0; < properties.length; i++)     {         // skip write or indexers         if (!properties[i].canread || properties[i].getindexparameters().length != 0)         {             continue;         }          var key = expression.constant(properties[i].name);         var value = expression.property(par, properties[i]);         // boxing must done manually... reference type isn't problem casting object         var valueasobject = expression.convert(value, typeof(object));         body.add(expression.call(dict, add, key, valueasobject));     }      // return value     body.add(dict);      var block = expression.block(new[] { dict }, body);      var lambda = expression.lambda<func<t, dictionary<string, object>>>(block, par);     return lambda.compile(); } 

use like:

public class test {     public int { get; set; }     public string b { get; set; } } 

and

func<test, dictionary<string, object>> fn = getvaluesfunc<test>();  var obj = new test {     = 5,     b = "foo" };  var res = fn(obj); 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -