【问题标题】:How can I get the Lists inside an Object? c#如何获取对象内的列表? C#
【发布时间】:2018-05-26 04:45:00
【问题描述】:

我有这个object

Object
 Adress - count = 2 - System.Collections.Generic.List<Address>
  [0]   Address
    City - "Text" - string
    State - "Text" - string
  [1]   Address
    City - "Text" - string
    State - "Text" -string
 Notes - "Text" - string
 Items - Type(Item)
  Item - count = 2 - System.Collections.Generic.List<Item>
   [0]  Item
    Name - "Text" - string
    Price - "Text" - string
   [1]  Item
    Name - "Text" - string
    Price - "Text" - string

在这个对象中,Address 是所有地址的列表,notes 只是对象的另一个字段,items 有一个名为 item 的子项,它里面包含 Lists,就像地址一样。

我通过这段代码得到了笔记的价值:

foreach (var item in (object as IEnumerable).Cast<object>().ToList())
                    {
    String substring = item.GetType().GetProperty("Notes").GetValue(item).ToString();
}

这是我从该方法传递给 List 时得到的返回:System.Collections.Generic.List1[Address]

但我无法访问列表,我需要将这个对象分隔在 X 列表中,如下所示:

Object2
 Adress
  [0]
  [1]

Object3
 Items
  Item
   [0]
   [1]

然后我可以使用上述方法获取值,有什么建议吗?我已经尝试了很多方法...

【问题讨论】:

  • 如果你能创建一个minimal reproducible example,那就太棒了。
  • 我需要从对象内部的列表中获取值,我无法获取,我只是从注释中获取值(那不是列表)
  • 我的foreach 只是将注释值返回给我,当它通过地址时,我返回:System.Collections.Generic.List1[Address]
  • 我认为至少您只需将您的 Object 的来源提供给我们,我们就可以帮助您。
  • 我的对象是在程序的另一部分创建的,它具有我在问题上写的那种结构,我怎样才能更好地解释? (我是堆栈新手)

标签: c# list object ienumerable getproperty


【解决方案1】:

只需将 Adress 属性的值转换为 List&lt;Object&gt;,就像这样

foreach (var item in (object as IEnumerable).Cast<object>().ToList())
{
    List<Object> address = item.GetType().GetProperty("Adress").GetValue(item) as List<Object>;
    foreach(var ad in address)
    {
        //do what you want here
    }
}

【讨论】:

  • List 地址 = item.GetType().GetProperty("Address").GetValue(item) as List;此获取为空。任何线索为什么?
  • 那是因为 Address 属性不是一个列表,检查它,像这样item.GetType().GetProperty("Address").GetValue(item).GetType()。也许是 IEnumerable 而不是 List。您必须检查该属性。
  • - item.GetType().GetProperty("Address").GetValue(item).GetType‌​() {Name = "List1" FullName = "System.Collections.Generic.List1[[Address, Address, Version=0.0. 0.0, Culture=neutral, PublicKeyToken=null]]"} System.Type {System.RuntimeType} 它似乎是一个列表
  • 然后像这样将其投射到 List
    List&lt;Address&gt; address = item.GetType().GetProperty("Address").GetValue(item) as List&lt;Address&gt;;
  • 当我将它投射到列表时它仍然返回 null,也许我做错了什么
猜你喜欢
  • 1970-01-01
  • 2021-08-29
  • 2012-10-31
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 2014-08-18
相关资源
最近更新 更多