简体   繁体   English

实现IEnumerable <T>对于List Wrapper

[英]Implement IEnumerable<T> For a List Wrapper

I have a class, which is just a wrapper over a list, ie, 我有一个类,它只是一个列表的包装,即,

public class Wrapper
{
   public List<int> TList
   {get;set;}
   public Wrapper()
   {
      TList=new List<int>();
   }
}

I want to make Wrapper inherits from IEnumerable so that I can use the following syntax: 我想让Wrapper从IEnumerable继承,以便我可以使用以下语法:

Wrapper wrapper = new Wrapper()
                       {
                         2,4,3,6 
                       };

Any idea how to which interface to implement IEnumerable<T> , or IEnumerable , and how to define the method body? 知道如何实现IEnumerable<T>IEnumerable ,以及如何定义方法体?

If you implement ICollection<int> you get the desired functionality. 如果实现ICollection<int> ,则可以获得所需的功能。

Correction: you actually only need to implement IEnumerable or IEnumerable<T> and have a public Add method in your class: 更正:您实际上只需要实现IEnumerableIEnumerable<T>并在您的类中使用公共Add方法:

public class Wrapper : IEnumerable<int>
{
    public List<int> TList
    { get; private set; }
    public Wrapper()
    {
        TList = new List<int>();
    }

    public void Add(int item)
    {
        TList.Add(item);
    }
    public IEnumerator<int> GetEnumerator()
    {
        return TList.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

(I also took the liberty of making the TList setter private; it is usually recommended that collection type properties are read-only so that the collection as such can not be substituted by any code outside the type.) (我也冒昧地将TList setter TList私有;通常建议集合类型属性是只读的,这样集合就不能被类型之外的任何代码替换。)

In order to get collection initializers you need to do 2 things: 为了获得集合初始化程序,您需要做两件事:

  1. Implement IEnumerable 实现IEnumerable
  2. Have a method called Add with the correct signature 有一个名为Add的方法,带有正确的签名

The preferable way to get these is to implement ICollection, but the minimum you need to do is: 获得这些的最佳方法是实现ICollection,但您需要做的最小事情是:

public class Wrapper : IEnumerable<int>
{
    public List<int> TList
    {get;set;}

    public IEnumerator<int> GetEnumerator()
    {
        return TList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() // Explicitly implement the non-generic version.
    {
        return TList.GetEnumerator();
    }

    public void Add(int i)
    {
         TList.Add(i);
    }

    public Wrapper()
    {
        TList=new List<int>();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM