简体   繁体   中英

Dynamically add a new dimension to array

I want to add a new dimension to my array aka. to my Matrix class based on user input in the constructor.

Example:

var matrix = new Matrix<int>(3,2,4); // is 3 dimensional array 

Here is my Matrix class:

class Matrix<T>
{
    private T[][] mArray;
    private readonly int mCols;
    private readonly int mRows;       

    public Matrix(params int[] args)
    {
        //here is what I ve tried.
        /*
        mCols = args[0];
        mRows = args[1];

        mArray = new T[mCols][];

        for (int i = 0; i < mCols; i++)
            mArray[i] = new T[mRows];
        */

        // how to create a multidimensional array based on "args" length?

    }
}

Question: how to create a multidimensional array based on "args" length?

Found it by looking here

Array.CreateInstance(typeof(YOUR_TYPE), params)

example:

var arr = Array.CreateInstance(typeof(int), 3, 2, 4); // creates a 3 dimensional array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM