实现IEnumerable< T>对于包装清单 [英] Implement IEnumerable<T> For a List Wrapper

查看:129
本文介绍了实现IEnumerable< T>对于包装清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>();
   }
}



我要让包装自IEnumerable 继承,这样我可以使用下面的语法:

I want to make Wrapper inherits from IEnumerable so that I can use the following syntax:

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



不知道如何实现的接口的IEnumerable< T> 的IEnumerable ,以及如何定义方法体?

Any idea how to which interface to implement IEnumerable<T>, or IEnumerable, and how to define the method body?

推荐答案

如果您实现 的ICollection< INT> 你所期望的功能。

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

更正:你其实只需要执行的IEnumerable 的IEnumerable< T> ,并在你的类中的公共添加方法:

Correction: you actually only need to implement IEnumerable or IEnumerable<T> and have a public Add method in your class:

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();
    }
}



(我也参加了制作的自由的的TList 设定部私人;它通常建议集合类型属性是只读使得集合因此不能由类型之外的任何代码被取代)

(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.)

这篇关于实现IEnumerable&LT; T&GT;对于包装清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆