C#動態修改數組維數

  1 using System;
 2 using System.Text;
 3 namespace ConsoleApplication2
 4 {
 5  class Class1
 6  {
 7   [STAThread]
 8   static void Main(string[] args)
 9   {
10    int[] arr=new int[]{1,2,3};
11    foreach(int x in arr)
12     Console.Write(x+" ");
13    Console.WriteLine();
14    arr=(int[])Redim(arr,5);
15    foreach(int x in arr)
16     Console.Write(x+" ");
17    Console.WriteLine();
18    arr=(int[])Redim(arr,2);
19    foreach(int x in arr)
20     Console.Write(x+" ");
21    Console.WriteLine();
22   }
23   public static Array Redim(Array origArray,int desiredSize)
24   {
25    Type t=origArray.GetType().GetElementType();
26    Array newArray=Array.CreateInstance(t,desiredSize);
27    Array.Copy(origArray,0,newArray,0,Math.Min(origArray.Length,desiredSize));
28    return newArray;
29   }
30  }
31 }

From: http://www.cnblogs.com/fxwdl/archive/2006/08/08/471287.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章