收录日期:2020/12/02 10:27:06 时间:2009-03-25 12:58:32 标签:c#,initialization

Lets say I have this class:

class MyList<T>
{

}

What must I do to that class, to make the following possible:

var list = new MyList<int> {1, 2, 3, 4};

Have an Add method and implement IEnumerable.

class MyList<T> : IEnumerable
{
  public void Add(T t)
  {

  }

  public IEnumerator GetEnumerator()
  {
    //...
  }
}

public void T()
{
  MyList<int> a = new MyList<int>{1,2,3};
}

Implementing ICollection on MyList will let the initalizer syntax work

class MyList<T> : ICollection<T>
{
}

Although the bare minimum would be:

public class myList<T> : IEnumerable<T>
{
    public void Add(T val)
    {
    }

    public IEnumerator<T> GetEnumerator()
    {
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
    }
}
ICollection<T> is also good.