【问题标题】:Making a Class Based on Arrays Enumerable in C#在 C# 中创建基于可枚举数组的类
【发布时间】:2013-10-05 00:09:26
【问题描述】:

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

我正在尝试使 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];
    }
}

【问题讨论】:

  • 你需要为你的班级实现IEnumerable。但是为什么不直接创建一个List<Employee> 而不是你自己的集合类呢?
  • 实现IEnumerable是什么意思?这听起来像是我需要做的。 (因为我想弄清楚这一点,所以我希望能够制作自己的集合类!)

标签: c# types enumerable


【解决方案1】:

我建议你坚持使用简单的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 page on them,它有一个很好的示例。

【讨论】:

    【解决方案2】:

    是这样的吗?顺便说一句,您不能将 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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-12
      • 2023-03-06
      • 2021-12-06
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多