how to create expression tree / lambda for a deep property from a string

后端 未结 5 1284
渐次进展
渐次进展 2020-12-13 16:07

Given a string: \"Person.Address.Postcode\" I want to be able to get/set this postcode property on an instance of Person. How can I do this? My idea was to split the string

5条回答
  •  庸人自扰
    2020-12-13 17:01

    Why you don't use recursion? Something like:

    setProperyValue(obj, propertyName, value)
    {
      head, tail = propertyName.SplitByDotToHeadAndTail(); // Person.Address.Postcode => {head=Person, tail=Address.Postcode}
      if(tail.Length == 0)
        setPropertyValueUsingReflection(obj, head, value);
      else
        setPropertyValue(getPropertyValueUsingReflection(obj, head), tail, value); // recursion
    }
    

提交回复
热议问题