加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 动态创建锯齿状矩形阵列

发布时间:2020-12-15 08:41:17 所属栏目:百科 来源:网络整理
导读:在我的项目中,我有很多这样的代码: int[][] a = new int[firstDimension][];for (int i=0; ifirstDimension; i++){ a[i] = new int[secondDimension];} 元素的类型是不同的. 有没有办法写一个像这样的方法 createArray(typeof(int),firstDimension,secondDi
在我的项目中,我有很多这样的代码:
int[][] a = new int[firstDimension][];
for (int i=0; i<firstDimension; i++)
{
  a[i] = new int[secondDimension];
}

元素的类型是不同的.

有没有办法写一个像这样的方法

createArray(typeof(int),firstDimension,secondDimension);

并获得新的int [firstDimension] [secondDimension]?

再一次,元素的类型仅在运行时才知道.

解决方法

泛型应该做的伎俩:
static T[][] CreateArray<T>(int rows,int cols)
{
    T[][] array = new T[rows][];
    for (int i = 0; i < array.GetLength(0); i++)
        array[i] = new T[cols];

    return array;
}

您必须在调用时指定类型:

char[][] data = CreateArray<char>(10,20);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读