动态创建锯齿状的矩形阵列 [英] Dynamically created jagged rectangular array

查看:145
本文介绍了动态创建锯齿状的矩形阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目,我有很多的code是这样的:

In my project I have a lot of code like this:

int[][] a = new int[firstDimension][];
for (int i=0; i<firstDimension; i++)
{
  a[i] = new int[secondDimension];
}

元素的类型是不同的。

有没有办法像写作的方法

Is there any way of writing a method like

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

和获得新INT [firstDimension] [secondDimension]

在再次,元件的类型仅在运行时已知

Once again, type of elements is known only at runtime.

推荐答案

泛型应该做的伎俩:

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;
}

您也必须指定调用这个时候,类型:

You do have to specify the type when calling this:

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

这篇关于动态创建锯齿状的矩形阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆