c# - 类似于 List<> 语法的对象初始化

标签 c# collections collection-initializer

我如何定义类,以便它可以像 List<T> 一样被初始化? :

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

例如,这个场景:

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

最佳答案

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

但是技术上来说,它只需要实现非泛型 IEnumerable接口(interface)并具有兼容的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 集合初始值设定项”部分.

关于c# - 类似于 List<> 语法的对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8635023/

相关文章:

c# - 具有通用对象的集合

c# - 我可以为属性使用集合初始值设定项吗?

c# - 在c#中检索xml文件中具有相同关键字的其他数据

c# - 在 C# 中使用 ref 数组参数与 COM 互操作

c# - 是否有针对 CLR 版本的 C# 预编译器定义

list - 将 TreeMap<String,Object> 转换为 List<HashMap<String,Object>>

c# - 从 Windows Phone 应用程序中的 DownloadStringCompleted 处理程序填充和返回实体

java - ArrayList 矩阵的自定义集合可迭代

c# - 如何确定对象初始值设定项是否是调用 Add 方法的初始值设定项?