欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#动态调整数组大小的方法

程序员文章站 2023-12-11 18:17:34
本文实例讲述了c#动态调整数组大小的方法。分享给大家供大家参考。具体如下: 通常,我们创建一个数组后就不能调整其长度,但是array类提供了一个静态方法createins...

本文实例讲述了c#动态调整数组大小的方法。分享给大家供大家参考。具体如下:

通常,我们创建一个数组后就不能调整其长度,但是array类提供了一个静态方法createinstance用来创建一个动态数组,所以我们可以通过它来动态调整数组的长度。

namespace arraymanipulation
{
 class program
 {
  static void main (string[] args)
  {
   int[] arr = new int[]{1,2,3};
   printarr(arr);
    arr = (int[])redim(arr,5);
   printarr (arr);
    arr = (int[]) redim (arr, 2);
   printarr (arr);
  )
  public static array redim (array origarray, int desiredsize)
  {
   //determine the type of element
   type t = origarray.gettype().getelementtype();
    //create a number of elements with a new array of expectations
   //new array type must match the type of the original array
   array newarray = array.createinstance (t, desiredsize);
    //copy the original elements of the array to the new array
   array.copy (origarray, 0, newarray, 0, math.min (origarray.length, desiredsize));
    //return new array
   return newarray;
  }
   //print array
  public static void printarr (int[] arr)
  {
   foreach (int x in arr)
   {
    console.write (x + ",");
   }
   console.writeline ();
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。

上一篇:

下一篇: