C# 为列表包装器实现 IEnumerable<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1892768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:41:23  来源:igfitidea点击:

Implement IEnumerable<T> For a List Wrapper

c#ienumerable

提问by Graviton

I have a class, which is just a wrapper over a list, i.e.,

我有一个类,它只是一个列表的包装器,即,

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

I want to make Wrapperinherits 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,以及如何定义方法体?

采纳答案by Fredrik M?rk

If you implement ICollection<int>you get the desired functionality.

如果您实施,ICollection<int>您将获得所需的功能。

Correction: you actually only need to implement IEnumerableor IEnumerable<T>and have a public Addmethod 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 TListsetter 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.)

(我还冒昧地将TListsetter 设为私有;通常建议集合类型属性是只读的,这样集合本身就不能被类型之外的任何代码替换。)

回答by ICR

In order to get collection initializers you need to do 2 things:

为了获得集合初始值设定项,您需要做两件事:

  1. Implement IEnumerable
  2. Have a method called Add with the correct signature
  1. 实现 IEnumerable
  2. 有一个名为 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>();
    }
}