列表的初始化使csc 2.0感到高兴

时间:2010-09-03 18:15:06

标签: c# list c#-2.0

我需要初始化一堆列表并在初始化期间用很多值填充它们,但我必须使用的csc 2.0编译器不喜欢它。例如:

List<int> ints = new List<int>() { 1, 2, 3 };

将产生以下编译器错误:

错误CS1002 :;预期

有没有办法初始化一个列表,这将使csc 2.0编译器满意,而不会做这样丑陋的事情:

List<int> ints = new List<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);

3 个答案:

答案 0 :(得分:10)

您正在使用一个名为集合初始化程序的功能,该功能已在C#3.0中添加,因此在C#2.0编译器中不存在。最接近语法的是使用传递给List<T>构造函数的显式数组。

List<int> ints = new List<int>(new int[] { 1, 2, 3 });

注意:此方法产生的代码与C#集合初始化程序版本大不相同。

答案 1 :(得分:2)

int[] values = { 1, 2, 3, 4 };
List<int> ints = new List<int>(values);

答案 2 :(得分:1)

由于您正在初始化一堆列表,因此请尽可能缩短语法。添加辅助方法:

 private static List<T> NewList<T>(params T[] items)
 {
     return new List<T>(items);
 }

这样称呼:

 List<int> ints = NewList(1,2,3);
 List<string> strings = NewList("one","two","three");
 // etc.