c# – 如何从字符串中创建深层属性的表达式树/ lambda

前端之家收集整理的这篇文章主要介绍了c# – 如何从字符串中创建深层属性的表达式树/ lambda前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给定一个字符串:“Person.Address.Postcode”我想能够获取/设置这个Postcode属性的一个实例的Person.我该怎么做?我的想法是将字符串拆分为“”.然后遍历这些部分,寻找先前类型的属性,然后构建一个表达式树,看起来像(对于伪语法的道歉):
(person => person.Address) address => address.Postcode

我有真正的麻烦,尽管创造了表情树!如果这是最好的方法,有人可以建议如何去做,还是有更简单的选择?

谢谢

安德鲁

public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }
    public Address Address{ get; set; }

    public Person()
    {
        Address = new Address();
    }
}

public class Address 
{
    public string Postcode { get; set; }
}

解决方法

为什么不使用递归?就像是:
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
}
原文链接:https://www.f2er.com/csharp/95340.html

猜你在找的C#相关文章