数组有一个很大的限制,即不能扩展数组以容纳超过其最初定义要容纳的项数。
因此,很多人使用"lists"作为替代方案。
我们可以在以下命名空间中找到 lists列表类:
System.Collections.Generic
这是"Generic"命名空间的链接
http://msdn.microsoft.com/en-us/library/system.collections.generic(v=vs.110).aspx.
"Generic"一词来自列表(以及队列,堆栈)可以保存任何类型的内置对象变量,例如,字符串,int,double,...等。
列表的类是:
http://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx.
与所有泛型一样,列表具有自己的语法风格……以尖括号的形式出现,“<=>”。在这些括号内,指定列表将包含的数据类型。
列表的工作方式是首先创建一个空列表,然后向其中添加项目。在以下示例中,我们创建了一个列表(ListOfRandomNumbers),用于保存一系列随机整数,例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace List
{
class Program
{
static void Main(string[] args)
{
// Here you can think of "List"
List ListOfRandomNumbers = new List();
// 首先我们创建一个随机类的实例
Random RandomNumberGenerator = new Random();
// 将随机数添加到列表中
for (int i=0; i {
ListOfRandomNumbers.Add(RandomNumberGenerator.Next());
}
// 使用列表类的"sort"方法对数字进行排序:
ListOfRandomNumbers.Sort();
foreach (int number in ListOfRandomNumbers)
{
Console.WriteLine(number);
}
}
}
}
列表通常可用作获取项列表作为方法的输出参数的一种方式。
列表也可以保存自定义对象,下面是一个示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace List
{
class Program
{
static void Main(string[] args)
{
// Here you can think of "List<int=>"
List<CountryStat=> ListOfCountryData = new List<CountryStat=>();
CountryStat EnglandObject = new CountryStat("London", 60000000, "English");
CountryStat FranceObject = new CountryStat("Paris", 90000000, "French");
CountryStat RussiaObject = new CountryStat("Moscow", 180000000, "Russian");
ListOfCountryData.Add(EnglandObject);
ListOfCountryData.Add(FranceObject);
ListOfCountryData.Add(RussiaObject);
foreach (CountryStat CountryData in ListOfCountryData)
{
Console.WriteLine(CountryData.Capital);
}
}
}
public class CountryStat
{
public string Capital { get; set; }
public int Population { get; set; }
public string Language { get; set; }
public CountryStat(string Capital, int Population, string Language)
{
this.Capital = Capital;
this.Population = Population;
this.Language = Language;
}
}
}
日期:2020-07-07 20:54:26 来源:oir作者:oir
