递归获取属性&对象的子属性
好吧,一开始我认为这很容易,也许确实如此,我只是太累了 - 但这就是我想做的。假设我有以下对象:
public class Container
{
public string Name { get; set; }
public List<Address> Addresses { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public List<Telephone> Telephones { get; set; }
}
public class Telephone
{
public string CellPhone { get; set; }
}
我需要做的是将容器属性名称“扁平化”为一个字符串(包括所有子属性和子属性的子属性),看起来像这样:
Container.Name, Container.Addresses.AddressLine1, Container.Addresses.AddressLine2, Container.Addresses.Telephones.CellPhone
这使得任何感觉?我似乎无法将它包裹在我的头上。
Ok so at first I thought this was easy enough, and maybe it is and I'm just too tired - but here's what I'm trying to do. Say I have the following objects:
public class Container
{
public string Name { get; set; }
public List<Address> Addresses { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public List<Telephone> Telephones { get; set; }
}
public class Telephone
{
public string CellPhone { get; set; }
}
What I need to be able to do, is 'flatten' Containers property names in to a string (including ALL child properties AND child properties of child properties) that would look something like this:
Container.Name, Container.Addresses.AddressLine1, Container.Addresses.AddressLine2, Container.Addresses.Telephones.CellPhone
Does that make any sense? I can't seem to wrap it around my head.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议你用自定义属性标记所有你需要抓取的类,然后你可以做这样的事情
I suggest you to mark all the classes, you need to grab, with custom attribute after that you could do something like this
根据我的评论,如果它始终是您想要链接到子类型的通用列表类型,您可以使用类似的东西。 IteratePropertiesRecursively 是给定类型的属性的迭代器,它将递归枚举该类型的属性以及通过通用列表链接的所有子类型。
注意:此代码将无法正确处理递归地将自身包含为其属性之一的类型的类型。正如 @Dementic 所指出的(谢谢!),尝试迭代此类类型将导致 StackOverflowException 。
Per my comment, you could use something like this if it will always be a generic List type that you want to link to a child type. IteratePropertiesRecursively is an iterator over the properties of the given type, that will recursively enumerate the properties of the type and all child types linked through a generic List.
Note: This code will not correctly handle a type that recursively includes itself as a type of one of its properties. Trying to iterate over such a type will result in a
StackOverflowException
, as pointed out by @Dementic (thanks!).