我将尝试使用任意字符串访问嵌套类结构的各个部分。
考虑以下(人为制造的)类:
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));
}