1

好的,在过去一个小时左右的时间里,我已经认真努力地理解了这一点。所以我想知道是否有人可以向我解释这一点。

我正在尝试使 C# 中的类成为可枚举的。具体来说,我正在尝试使其与 foreach 循环一起使用。我有一个使用简单类的测试,将字符放入构造函数中。

EmployeeArray ArrayOfEmployees = new EmployeeArray('a','b','c');

foreach(char e in EmployeeArray) //Nope, can't do this!
{
Console.WriteLine(e);
}

//---Class Definition:---

class EmployeeArray
{
    private char[] Employees;
    public EmployeeChars(char[] e)
    {
        this.Employees = e;
    }
    //Now for my attempt at making it enumerable:
    public IEnumerator GetEnumerator(int i)
    {
        return this.Employees[i];
    }
}
4

2 回答 2

0

我建议你坚持使用简单的List<>. 这是一个通用的集合结构,可以为您完成所有繁重的工作。实际上,在您完全了解系统的工作原理之前,制作自己的 IEnumerables 是没有意义的。

首先,将您的类更改为它代表一个项目:

public class Employee
{
    public string Name {get;set;}
    //add additional properties
}

然后做一个List<Employee>对象

List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { Name = "John Smith" });

foreach(Employee emp in employees)
    Console.WriteLine(emp.Name);

如果您确实想制作自己的 IEnumerable,请查看它们上的msdn 页面,其中有一个很好的示例。

于 2013-09-28T22:02:59.917 回答
0

是这样的吗?顺便说一句,您不能将 Class 用作集合,因为它是一种类型。您需要使用声明的变量来访问它。

// You cant use EmployeeArray, instead use ArrayOfEmployees 
foreach(char e in **EmployeeArray**) 
{
   Console.WriteLine(e);
}

无论如何,这就是我的做法。

class Program
    {
        static void Main(string[] args)
        {
            Collection collect = new Collection(new string[]{"LOL1","LOL2"});
            foreach (string col in collect)
            {
                Console.WriteLine(col + "\n");
            }
            Console.ReadKey();
        }
    }

    public class Collection : IEnumerable
    {
        private Collection(){}
        public string[] CollectedCollection { get; set; }
        public Collection(string[] ArrayCollection)
        {
            CollectedCollection = ArrayCollection;
        }

        public IEnumerator GetEnumerator()
        {
            return this.CollectedCollection.GetEnumerator();
        }
    }
于 2013-09-29T03:17:10.467 回答