📜  C#| ArrayList,其元素为指定值的副本

📅  最后修改于: 2021-05-29 16:10:04             🧑  作者: Mango

ArrayList.Repeat(Object,Int32)方法用于返回一个ArrayList,其元素是指定值的副本。或者换句话说,当您要重复ArrayList中的指定元素时,使用此方法。此方法是O(n)运算,其中n是应复制项目的次数。

句法:

public static ArrayList Repeat (object item, int count);

参数:

返回值:该方法返回一个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);
    }
}

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.repeat?view=netframework-4.7.2