欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#動態(tài)調(diào)整數(shù)組大小的方法

 更新時間:2015年04月02日 14:27:45   作者:令狐不聰  
這篇文章主要介紹了C#動態(tài)調(diào)整數(shù)組大小的方法,涉及C#中靜態(tài)方法CreateInstance的使用技巧,非常具有實(shí)用價值,需要的朋友可以參考下

本文實(shí)例講述了C#動態(tài)調(diào)整數(shù)組大小的方法。分享給大家供大家參考。具體如下:

通常,我們創(chuàng)建一個數(shù)組后就不能調(diào)整其長度,但是Array類提供了一個靜態(tài)方法CreateInstance用來創(chuàng)建一個動態(tài)數(shù)組,所以我們可以通過它來動態(tài)調(diào)整數(shù)組的長度。

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#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論