首页 > 解决方案 > C#如何为嵌套类实现IEnumerable

问题描述

我有一组相当简单的类,只有属性,例如:

using System;               //main data types
using System.Reflection;    //to iterate through all properties of an object
using System.Collections;   //for IEnumerable implementation?

namespace ConsoleApp1
{
    public class WholeBase //: IEnumerable ?
    {
        public SomeHeaders Headers { get; set; }
        public SomeBody Body { get; set; }
    }

    public partial class SomeHeaders
    {
        public string HeaderOne { get; set; }
        public string HeaderTwo { get; set; }
    }

    public partial class InSet
    {
        public string AllForward { get; set; }
        public string Available { get; set; }
    }

    public partial class SomeBody
    {
        public InSet MySet { get; internal set; }
        public Boolean CombinedServiceIndicator { get; set; }
        public int FrequencyPerDay { get; set; }
        public string ValidUntil { get; set; }
    }

我试图获取所有属性和值,但似乎我被卡住了,因为 IEnumerable 或缺少某些东西。这是我迄今为止尝试过的:填充属性并尝试遍历所有属性和值,但是,不起作用......

  public class Program
{
    //...
    public static void Main(string[] args)
    {
        WholeBase NewThing = new WholeBase();
        NewThing.Headers = new SomeHeaders { HeaderOne = "First", HeaderTwo = "Second" };

        NewThing.Body = new SomeBody
        {
            MySet = new InSet { AllForward = "YES", Available = "YES"},
            CombinedServiceIndicator = false,
            FrequencyPerDay = 10,
            ValidUntil = "2019-12-31"
        };

        void SeeThrough(WholeBase myBase)
        {
            //iterate through all the properties of NewThing
            foreach (var element in myBase)
            {
                foreach (PropertyInfo prop in myBase.GetType().GetProperties())
                {
                    var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                    Console.WriteLine(prop.GetValue(element, null).ToString());
                }
            }
        };
    }
}

标签: c#

解决方案


好吧,您似乎在想“嗯,我将遍历类 'A' 的所有属性值,同时使用反射来获取类 'A' 的所有属性,然后对于每个属性,我将显示其值。”

这里有很多问题。

首先 - 循环所有值只能使用实现接口的对象,IEnumerable但您并不真正需要它。由于您使用反射获取其所有属性,因此您也可以使用它来获取值:

foreach (PropertyInfo prop in myBase.GetType().GetProperties())
{
    // this returns object
    var element = prop.GetValue(myBase, null);
    Console.WriteLine(element);
}

其次 -ToString()不知道如何显示对象的字段,除非对象覆盖它。

虽然上面的代码可以编译和工作,但是因为 element 是一个对象而不是原始类型,除非你重写了这个方法,.ToString这个调用Console.WriteLine只会显示类型的名称。

您可以再次循环遍历该对象的所有属性,并最终为每个属性获取一个值:

foreach (var childProperty in element.GetType().GetProperties())
{
   Console.WriteLine(childProperty.GetValue(element, null).ToString());
}

推荐阅读