我试图使用任意字符串访问嵌套类结构的各个部分.
给出以下(设计的)类:
public class Person { public Address PersonsAddress { get; set; } } public class Adddress { public PhoneNumber HousePhone { get; set; } } public class PhoneNumber { public string Number { get; set; } }
我想要从Person对象的一个实例的“PersonsAddress.HousePhone.Number”获取对象.
目前我正在使用反思来做一些简单的递归查找,但是我希望有一些忍者有更好的想法.
作为参考,这里是我开发的(crappy)方法:
private static object ObjectFromString(object basePoint,IEnumerable<string> pathToSearch) { var numberOfPaths = pathToSearch.Count(); if (numberOfPaths == 0) return null; var type = basePoint.GetType(); var properties = type.GetProperties(); var currentPath = pathToSearch.First(); var propertyInfo = properties.FirstOrDefault(prop => prop.Name == currentPath); if (propertyInfo == null) return null; var property = propertyInfo.GetValue(basePoint,null); if (numberOfPaths == 1) return property; return ObjectFromString(property,pathToSearch.Skip(1)); }
解决方法
您可以简单地使用标准的.NET
DataBinder.Eval Method,像这样:
object result = DataBinder.Eval(myPerson,"PersonsAddress.HousePhone.Number");