mercredi 19 septembre 2018

Updating nested property value via a string path using expression

The Problem to solve

I want to be able to update the property prop using the fictive method Update. To do so, i would like to call the method like this:

Root obj = /* ... */;
Update(obj, "sub/sub/prop", "foobar");

How would i eg. build some Expression tree to do this?

Scenario

class Sub2
{
    public string prop { get; set; }
}
class Sub1
{
    public Sub2 sub { get; set; }
}
class Root
{
    public Sub1 sub { get; set; }
}
class Main
{
    //...
    void Update(object obj, string navigation, object newval) { /* magic */ }
}

Full Problem

I need to be able to serialize single fields from some object (already solved, method head public void Serialize<TProperty>(T obj, Stream s, Expression<Func<T, TProperty>> exp)) and update a corresponding field on a server application. Only that field is allowed to be updated, some classes are nested way too deep to allow for solutions like "just use some ID stuff and a switch to then put the value into the right field" which is why this approach was chosen.





Aucun commentaire:

Enregistrer un commentaire