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

本文关键字:语法 List 初始化 类似于 对象 | 更新日期: 2023-09-27 18:18:45

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

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

。,这个场景:

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

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

通常,为了允许直接在Class上使用集合初始化器语法,它将实现一个集合接口,如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;

有关详细信息,请参见语言规范的"7.6.10.3集合初始化器"一节。

如果您将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()//... }}

你选择哪一个取决于你如何建模一个类。

我没有看到任何人建议泛型实现,所以在这里。

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