对象初始化类似于List<>句法

时间:2011-12-26 10:49:45

标签: c# collections collection-initializer

如何定义类,以便像List<T>一样初始化类:

List<int> list = new List<int>(){ //this part };

例如,这种情况:

Class aClass = new Class(){ new Student(), new Student()//... };

3 个答案:

答案 0 :(得分:6)

通常,为了直接在Class上允许collection-initializer语法,它会实现一个集合接口,例如ICollection<Student>或类似的(例如继承自Collection<Student>)。

技术上说,它只需要实现非通用的IEnumerable接口并具有兼容的Add方法。

所以这就足够了:

using System.Collections;

public class Class : IEnumerable
{
    // This method needn't implement any collection-interface method.
    public void Add(Student student) { ... }  

    IEnumerator IEnumerable.GetEnumerator() { ... }
}

用法:

Class aClass = new Class { new Student(), new Student()  };

正如您所料,编译器生成的代码类似于:

Class temp = new Class();
temp.Add(new Student());
temp.Add(new Student());
Class aClass = temp;

有关详细信息,请参阅language specification的“7.6.10.3集合初始值设定项”部分。

答案 1 :(得分:1)

如果您将MyClass定义为学生集合:

public class MyClass : List<Student>
{
}

var aClass = new MyClass{  new Student(), new Student()//... }

或者,如果您的班级包含Student的公开收藏:

public class MyClass
{
  public List<Student> Students { get; set;}
}

var aClass = new MyClass{ Students = new List<Student>
                                     { new Student(), new Student()//... }}

您选择哪一个实际取决于您对班级建模的方式。

答案 2 :(得分:0)

我没有看到有人提出仿制药的实施,所以就在这里。

    class Class<T>  : IEnumerable
{
    private List<T> list;
    public Class()
    {
        list = new List<T>();
    }

    public void Add(T d)
    {
        list.Add(d);
    }

    public IEnumerator GetEnumerator()
    {
        return list.GetEnumerator();
    }
}

并使用:

Class<int> s = new Class<int>() {1,2,3,4};