【发布时间】:2011-08-18 03:33:08
【问题描述】:
我正在尝试使用 任意 字符串访问嵌套类结构的各个部分。
给定以下(人为的)类:
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" 的对象。
目前我正在使用反射进行一些时髦的递归查找,但我希望那里的一些忍者有一些更好的想法。
作为参考,这是我开发的(糟糕的)方法:
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));
}
【问题讨论】:
-
你认为你为什么需要这样做?
-
@Steve - 因为我需要控制任意类型的投影,而配置是最好的地方。
-
这对于实现通用数据绑定机制也很有用 - BindingSource 的 DataMember 属性接受这样的导航路径字符串。
标签: c# reflection