初始化集合的简明方法

时间:2011-05-27 13:47:39

标签: c# collections

我可以使用类似的东西以简洁的方式初始化一个类:

public static readonly type TYPE_NAME = new type()
        {
            ClientIp = "ClientIp",
            LanguageCode = "LanguageCode",
            SessionToken = "SessionToken",
            SystemKey = "SystemKey"
        };

然而,是否可以以类似的方式初始化集合(继承自List<>)?

4 个答案:

答案 0 :(得分:8)

List<string> strList = new List<string>{ "foo", "bar" };

List<Person> people = new List<Person>{
                                new Person { Name = "Pete", Age = 12},
                                new Person { Name = "Jim", Age = 15}
                      };

答案 1 :(得分:0)

使用集合初始值设定项

http://msdn.microsoft.com/en-us/library/bb384062.aspx

List<int> list = new List<int> { 1, 2, 3 };

答案 2 :(得分:0)

是:

var l = new List<int>() { 1, 1, 2, 3, 5 };

答案 3 :(得分:0)

您肯定可以使用集合初始化程序。 要使用它,

List<int> collection=  List<int>{1,2,3,...};

要使用集合初始值设定项,它不必完全是List类型。 集合初始值设定项可用于那些实现IEnumerable并具有一个公共Add方法的类型。

即使在以下类型中也使用了Collection初始化程序功能。

public class SomeUnUsefulClass:IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }
        public void Add(int i)
        {
            //It does not do anything.
        }
    }

像,

 SomeUnUsefulClass cls=new SomeUnUsefulClass(){1,2,3,4,5};

完全有效。

相关问题