C#在Collection 中的指定索引处插入元素
给定Integer的Collection<T>,我们必须在给定的索引处插入一个元素。
要在Collection<T>中插入元素,我们使用Insert()方法,它接受两个参数index和item,其中index是整数类型,而item是T类型,即Collection<T>的类型。
语法:
public void Insert (int index, T item);
注意:如果index小于0或大于count,则Insert()方法可能返回异常(ArgumentOutOfRangeException)。
用C#代码在Collection<T>中插入元素
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class Nhooo
{
public static void Main()
{
// 声明整数的集合
Collection<int> iColl = new Collection<int>();
// 向集合中添加元素
iColl.Add(100);
iColl.Add(200);
iColl.Add(300);
iColl.Add(400);
// 显示元素总数
Console.WriteLine("元素总数: " + iColl.Count);
// 显示所有元素
foreach (int ele in iColl)
{
Console.WriteLine(ele);
}
// 现在在第三索引处插入900
iColl.Insert(3, 900);
// 显示元素总数
Console.WriteLine("元素总数: " + iColl.Count);
// 显示所有元素
foreach (int ele in iColl)
{
Console.WriteLine(ele);
}
}
}输出结果
元素总数: 4 100 200 300 400 元素总数: 5 100 200 300 900 400
显示异常
在这里,我们将在-1索引处插入一个元素,该元素将生成“ArgumentOutOfRangeException”异常。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class nhooo
{
public static void Main()
{
// 声明整数的集合
Collection<int> iColl = new Collection<int>();
// 向集合中添加元素
iColl.Add(100);
iColl.Add(200);
iColl.Add(300);
iColl.Add(400);
// 显示元素总数
Console.WriteLine("Total number of elements: " + iColl.Count);
// 显示所有元素
foreach (int ele in iColl)
{
Console.WriteLine(ele);
}
// 现在在-1索引处插入900
// 会产生异常
iColl.Insert(-1, 900);
// 显示元素总数
Console.WriteLine("Total number of elements: " + iColl.Count);
// 显示所有元素
foreach (int ele in iColl)
{
Console.WriteLine(ele);
}
}
}输出结果
Total number of elements: 4
100
200
300
400
Unhandled Exception:
System.ArgumentOutOfRangeException: Index must be within the bounds of the List.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException
(System.ExceptionArgument argument,System.ExceptionResourceresource) [0x00029]
in <65984520577646ec9044386ec4a7b3dd>:0
at System.Collections.ObjectModel.Collection`1[T].Insert (System.Int32 index, T item)
[0x00026] in <65984520577646ec9044386ec4a7b3dd>:0
atnhooo.Main() [0x0007f] in <d658237a48934373b441d64c47cad823>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException:
Index must be within the bounds of the List.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException
(System.ExceptionArgument argument,System.ExceptionResourceresource) [0x00029]
in <65984520577646ec9044386ec4a7b3dd>:0
at System.Collections.ObjectModel.Collection`1[T].Insert (System.Int32 index, T item)
[0x00026]
in <65984520577646ec9044386ec4a7b3dd>:0
atnhooo.Main() [0x0007f] in <d658237a48934373b441d64c47cad823>:0热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短