c# - Dynamically evaluating a property string with Expressions -


how build expression fulfill following goal:

public object eval(object rootobj, string propertystring)

eg: eval(person, "address.zipcode") => return person.address.zipcode

expression.propertyorfield doesn't work because don't have type of each intermediate property. i'd avoid creating dependency on scripting library.

i want try use expressions because allow me store cache of these expression trees executed several times. i'm aware it's possible iteratively or recursively reflection.

it sounds you're looking this:

public object eval(object root, string propertystring) {     var propertynames = propertystring.split('.');     foreach(var prop in propertynames)     {         var property = root.gettype().getproperty(prop);         if (property == null)         {             throw new exception(...);         }          root = property.getvalue(root, null);     }      return root; } 

to create expression use this:

public expression eval(object root, string propertystring) {     var propertynames = propertystring.split('.');     parameterexpression param = expression.parameter(root.gettype, "_");     expression property = param;     foreach(var prop in propertyname)     {         property = expression.propertyorfield(property, prop);     }      return expression.lambda(property, param); } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -