C# ArrayList - Add() 方法
C# ArrayList add() 方法将一个对象添加到数组列表的末尾。当对象添加到 ArrayList 时,此方法返回添加值的索引。
语法
以下是 C# ArrayList Add() 方法的语法 -
public virtual int Add (object? value);
参数
此方法接受一个参数,该参数是一个值,表示要添加到数组末尾的对象 -
返回值
此方法返回已添加值的 ArrayList 的索引。
示例 1:在 ArrayList 中添加整数
这是 ArrayList Add() 方法的基本示例。我们可以使用此方法在 arrayList 中添加对象 -
using System; using System.Collections; public class SamplesArrayList { public static void Main() { // 创建并初始化一个新的 ArrayList。 ArrayList myArrayList = new ArrayList(); // 使用添加方法 myArrayList.Add(1); myArrayList.Add(2); myArrayList.Add(3); myArrayList.Add(4); // 显示 ArrayList。 Console.WriteLine("The ArrayList contains the following:"); PrintValues(myArrayList, ' '); } public static void PrintValues(IEnumerable myList, char mySeparator) { foreach(object obj in myList) { Console.Write("{0}{1}", mySeparator, obj); } Console.WriteLine(); } }
输出
以下是输出 -
The ArrayList contains the following: 1 2 3 4
示例 2:在 ArrayList 中添加字符串
让我们看另一个使用 ArrayList 的 Add() 方法的示例,该示例用于在 ArrayList 中添加字符串值 -
using System; using System.Collections; public class SamplesArrayList { public static void Main() { // 创建并初始化一个新的 ArrayList。 ArrayList myArrayList = new ArrayList(); // 使用添加方法 myArrayList.Add("Hello"); myArrayList.Add("TutorialsPoint"); myArrayList.Add("India"); myArrayList.Add("Hyderabad"); // 显示 ArrayList。 Console.WriteLine("The ArrayList contains the following:"); PrintValues(myArrayList, ' '); } public static void PrintValues(IEnumerable myList, char mySeparator) { foreach(object obj in myList) { Console.Write("{0}{1}", mySeparator, obj); } Console.WriteLine(); } }
输出
以下是输出 -
The ArrayList contains the following: Hello TutorialsPoint India Hyderabad
示例 3:获取索引值
在此示例中,我们使用 Add() 方法检索 ArrayList 中添加元素的索引 -
using System; using System.Collections; public class SamplesArrayList { public static void Main() { // 创建并初始化一个新的 ArrayList。 ArrayList myArrayList = new ArrayList(); // 使用添加方法 int indx1 = myArrayList.Add("TutorialsPoint"); int indx2 = myArrayList.Add("India"); // 显示索引。 Console.WriteLine("Index Value of the Added element is {0}, and {1}:", indx1, indx2); } }
输出
以下是输出 -
Index Value of the Added element is 0, and 1:
示例 4:向 ArrayList 添加混合数据类型
在此示例中,我们使用 Add() 方法在 ArrayList 中添加不同数据类型的对象 -
using System; using System.Collections; public class Example { public static void Main() { // 创建一个 ArrayList ArrayList myArrayList = new ArrayList(); // 将不同类型的对象添加到 ArrayList myArrayList.Add("Hello"); myArrayList.Add(80); myArrayList.Add(3.14); myArrayList.Add(DateTime.Now); myArrayList.Add(null); // 显示ArrayList中的元素 Console.WriteLine("ArrayList contents:"); foreach (object item in myArrayList) { Console.WriteLine(item == null ? "null" : item.ToString()); } // 添加新对象并获取其索引 int index = myArrayList.Add("New Item"); Console.WriteLine($"The new item was added at index: {index}"); } }
输出
以下是输出 -
ArrayList contents: Hello 80 3.14 1/22/2025 11:29:31 AM null The new item was added at index: 5