如何在C#中获取对象的多个子项的枚举器

本文关键字:枚举 取对象 获取 | 更新日期: 2023-09-27 18:25:18

这是我的类

class EmissionSource:IEnumerable
{
    private Emissions[] emissions = new Emissions[5];
    private Contribution[] contributions = new Contribution[2];
    public EmissionSource()
    {
        emissions[0] = new Emissions(2010, 400, 200, 6);
        emissions[1] = new Emissions(2011, 450, 255, 16);
        emissions[2] = new Emissions(2012, 470, 245, 26);
        emissions[3] = new Emissions(2013, 490, 285, 36);
        emissions[4] = new Emissions(2014, 495, 245, 46);

        contributions[0] = new Contribution(1, "Energy");
        contributions[1] = new Contribution(3, "Industrial Sector");
    }
    public IEnumerator GetEnumerator()
    {
        return emissions.GetEnumerator();
    }
}

在GetEnumerator方法中,我使用emissions对象将请求委派给System.Array。我想知道,我如何迭代其他子项,即等贡献

    foreach (Emissions e in source)
    {
        //
    }
    foreach (Contribution e in source)
    {
       //
    }

如何在C#中获取对象的多个子项的枚举器

我能想到的最好的方法就是使用两个不同的属性:

class Main
{
    class X
    {
        private int[] i = new int[5];
        private string[] s = new string[2];
        public X()
        {
            i[0] = 0; i[1] = 1; i[2] = 2; i[3] = 3; i[4] = 4;
            s[0] = "test"; s[1] = "test2";
        }
        public IEnumerable<string> Strings
        {
            get
            {
                return s;
            }
        }
        public IEnumerable<int> Ints
        {
            get
            {
                return i;
            }
        }
    }
    private static void Main(string[] args)
    {
        X x = new X();
        foreach (string s in x.Strings)
        { }
        foreach (int i in x.Ints)
        { }
    }
}

我尝试过使用IEnumerable的泛型版本并从int和string继承,但我无法实现这一点,可能是因为泛型版本再次从非泛型IEnumerale继承,使其成为菱形继承树。也许你可以把它当作思考的食物。

class X : IEnumerable<int>, IEnumerable<string>
{
            private int[] i = new int[5];
            private string[] s = new string[2];
            public X()
            {
                i[0] = 0; i[1] = 1; i[2] = 2; i[3] = 3; i[4] = 4;
                s[0] = "test"; s[1] = "test2";
            }
            public IEnumerator GetEnumerator()
            {
                return i.GetEnumerator();
            }
            IEnumerator<int> IEnumerable<int>.GetEnumerator()
            {
                return (IEnumerator<int>)i.GetEnumerator();
            }
            IEnumerator<string> IEnumerable<string>.GetEnumerator()
            {
                return (IEnumerator<string>)i.GetEnumerator();
            }
}