我如何定义类,以便它可以像 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/