📅  最后修改于: 2023-12-03 15:25:18.310000             🧑  作者: Mango
在 C# 中,可以使用 List
在 C# 中,可以使用以下语法来创建 List
List<T> myList = new List<T>();
其中,T 是列表中包含的对象的数据类型。例如,如果要创建一个包含字符串的列表,则可以使用以下代码:
List<string> myList = new List<string>();
在 C# 中,可以使用以下语法将对象添加到 List
myList.Add(item);
其中,item 是要添加到列表中的对象。例如,要将字符串 "hello" 添加到包含字符串的列表中,可以使用以下代码:
myList.Add("hello");
下面是一个完整的示例,演示如何将数字添加到包含数字的列表中:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// 添加数字到列表中
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// 输出列表中的数字
foreach(int number in numbers)
{
Console.WriteLine(number);
}
}
}
输出:
1
2
3
使用 List