加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:50:10 所属栏目:百科 来源:网络整理
导读:如何定义类,以便像List T一样初始化它: Listint list = new Listint(){ //this part }; 例如,这种情况: Class aClass = new Class(){ new Student(),new Student()//... }; 解决方法 通常,为了直接在Class上允许 collection-initializer语法,它将实现集合
如何定义类,以便像List< T>一样初始化它:

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

例如,这种情况:

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

解决方法

通常,为了直接在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集合初始值设定项”部分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读