c# – 通过字符串在对象图中查找属性

我试图使用任意字符串访问嵌套类结构的各个部分.

给出以下(设计的)类:

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");

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...