zoukankan      html  css  js  c++  java
  • C#动态分配一维数组和二维数组函数

     

     //动态调整一维数组长度
        public static Array Redim(Array origArray, int length)
        {
            //确定每个元素的类型
            Type t = origArray.GetType().GetElementType();
            //创建新的数组
            Array newArray = Array.CreateInstance(t, length);
            //原数组中的数据拷贝到新数组中
            Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, length));
            return newArray;
        }


        //动态调整二维数组长度
        public static Array Redim(Array origArray, params int[] lengths)
        {
            //确定每个元素的类型
            Type t = origArray.GetType().GetElementType();
            //创建新的数组
            Array newArray = Array.CreateInstance(t, lengths);
            //原数组中的数据拷贝到新数组中
            for (int i = origArray.GetLowerBound(0); i <= Math.Min(origArray.GetUpperBound(0), newArray.GetUpperBound(0)); i++)
                for (int j = origArray.GetLowerBound(1); j <= Math.Min(origArray.GetUpperBound(1), newArray.GetUpperBound(1)); j++)
                    newArray.SetValue(origArray.GetValue(i, j), i, j);
            //在这里没有用Copy方法,如果用此方法,会把原数组中所有数据逐个拷贝到新数组中                 
            return newArray;
        }

        //如果在Redim方法中用Copy方法(动态调整二维数组长度)
        public static Array Redim(Array origArray, params int[] lengths)
        {
            int length = 1;
            for (int i = 0; i < lengths.Length; i++)
                length *= lengths;
            Type t = origArray.GetType().GetElementType();
            Array newArray = Array.CreateInstance(t, lengths);
            Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, length));
            return newArray;
        }

  • 相关阅读:
    事件回顾
    把时间花在经典上
    事件回顾
    硬件毛刺
    事件回顾
    cache支持三种pre-fetch方式:normal/pre-fetch1/pre-fetch2-way1/pre-fetch-way2
    cache支持single/increment/increment4三种方式传输
    计算机必读书籍
    那些让我们如此享受的慢性毒药(转载)
    平淡节制
  • 原文地址:https://www.cnblogs.com/madengwei/p/1218349.html
Copyright © 2011-2022 走看看