通过字符串在对象图中查找属性 [英] Lookup property in object graph via a string

查看:27
本文介绍了通过字符串在对象图中查找属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to access various parts of a nested class structure using a arbitrary string.

给定以下(人为的)类:

Given the following (contrived) classes:

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" 中的对象.

I'd like to be able to get the object at "PersonsAddress.HousePhone.Number" from an instance of the Person object.

目前我正在使用反射进行一些时髦的递归查找,但我希望那里的一些忍者有一些更好的想法.

Currently I'm doing some funky recursive lookup using reflection, but I'm hoping that some ninjas out there have some better ideas.

作为参考,这是我开发的(蹩脚的)方法:

For reference, here is the (crappy) method I've developed:

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 方法,像这样:

You could simply use the standard .NET DataBinder.Eval Method, like this:

object result = DataBinder.Eval(myPerson, "PersonsAddress.HousePhone.Number");

这篇关于通过字符串在对象图中查找属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆