我有一个看起来像这样的方法:
public string Bid(AdapterRequest adapterRequest)
{
string property = "adapterRequest.Lead.Contact.ZipCode";
string zipCode = ???
}
如何从字符串值中获取adapterRequest.Lead.Contact.ZipCode
的值?
答案 0 :(得分:1)
您可以使用带递归的反射:
public string Bid(AdapterRequest adapterRequest)
{
string propertyChain = "Lead.Contact.ZipCode";
string zipCode = ResolvePropertyChain(propertyChain.Split('.').ToList(), adapterRequest) as string;
// ... assuming other logic exists here ...
}
public object ResolvePropertyChain(List<string> propertyChain, object source)
{
object propertyValue = null;
if (source != null)
{
propertyValue = source.GetType().GetProperty(propertyChain[0]).GetValue(source, null);
if (propertyValue != null && propertyChain.Count > 1)
{
List<string> childPropertyChain = new List<string>(propertyChain);
childPropertyChain.RemoveAt(0);
propertyValue = ResolvePropertyChain(childPropertyChain, propertyValue);
}
}
return propertyValue;
}
答案 1 :(得分:-3)
string zipCode = (string)adapterRequest.GetType().GetProperty(property).GetValue(adapterRequest, null);
请注意,这不适用于您的情况,因为您有一个对象层次结构,但您可以将属性拆分为多个部分并逐个获取对象,并在最新检索到的对象上重复查询下一部分 - GetType将在非空值。