ArrayList.Repeat(Object,Int32)方法用于返回一个ArrayList,其元素是指定值的副本。或者换句话说,当您要重复ArrayList中的指定元素时,使用此方法。此方法是O(n)运算,其中n是应复制项目的次数。
句法:
public static ArrayList Repeat (object item, int count);
参数:
item: It is an Object to copy multiple times in the new ArrayList. The value can be null.
count: It counts the number of times item should be copied.
返回值:该方法返回一个ArrayList,其中包含数量计数的元素,所有元素都是item的副本。
异常:如果count的值小于零,则此方法将提供ArgumentOutOfRangeException 。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# program to illustrate the use of
// ArrayList.Repeat(Object, Int32) Method
using System;
using System.Collections;
class GFG {
// Main method
public static void Main()
{
// Create and repeat the element
// of ArrayList "mylist"
ArrayList mylist = ArrayList.Repeat("GFG", 6);
// Display element
foreach(Object ob in mylist)
{
Console.WriteLine(ob);
}
// Display and count the total number of element
Console.WriteLine("The count of the item is : {0}", mylist.Count);
}
}
输出:
GFG
GFG
GFG
GFG
GFG
GFG
The count of the item is : 6
范例2:
// C# program to illustrate the use of
// ArrayList.Repeat(Object, Int32) Method
using System;
using System.Collections;
class GFG {
// Main method
public static void Main()
{
// Create and repeat the
// element of mylist ArrayList
// this will give runtime error
// as count is less than 0
ArrayList mylist = ArrayList.Repeat(43, -1);
// Display element
foreach(Object ob in mylist)
{
Console.WriteLine(ob);
}
// Display and count the total number of element
Console.WriteLine("The count of the item is : {0}", mylist.Count);
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: count
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.repeat?view=netframework-4.7.2