如何创建表达式树/λ为一个字符串的深物业 [英] how to create expression tree / lambda for a deep property from a string
问题描述
给定一个字符串:Person.Address.Postcode我希望能够得到有关人士的一个实例/设置此邮政编码属性。我怎样才能做到这一点?我的想法是分裂的字符串。然后遍历部分,找上一类型的属性,然后建立一个表达式树看起来是这样的(道歉伪语法):
(人=> person.Address)地址= GT; address.Postcode
我有真正的麻烦实际上可以创造表达式树,但!如果这是最好的办法,有人可以建议如何去做,还是有更简单的方法吗?
感谢
安德鲁
公共类Person
{
公众诠释年龄{搞定;组; }
公共字符串名称{;组; }
公共地址地址{搞定;组; }
公众人物()
{
地址=新地址();
}
}
公共类地址
{
公共字符串邮编{搞定;组; }
}
你为什么不使用递归?是这样的:
setProperyValue(OBJ,propertyName的,值)
{
头,尾= propertyName的。 SplitByDotToHeadAndTail(); // Person.Address.Postcode => {头=人,尾= Address.Postcode}
如果(tail.Length == 0)
setPropertyValueUsingReflection(OBJ,头,价值);
,否则
setPropertyValue(getPropertyValueUsingReflection(OBJ,头),尾值); //递归
}
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 by "." and then iterate over the parts, looking for the property on the previous type, then build up an expression tree that would look something like (apologies for the pseudo syntax):
(person => person.Address) address => address.Postcode
I'm having real trouble acutally creating the expression tree though! If this is the best way, can someone suggest how to go about it, or is there an easier alternative?
Thanks
Andrew
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; }
}
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
}
这篇关于如何创建表达式树/λ为一个字符串的深物业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!