Generic printing of jagged arrays

倾然丶 夕夏残阳落幕 提交于 2019-12-05 19:56:51

You can do it using dynamics:

    void Main()
    {
        Print(new double[][]
        {
            new double[] { 1, 2 },
            new double[] { 3, 4 },
            new double[] { 5, 6 },
        });

        // Output: [ 1, 2 ]
        //         [ 3, 4 ]
        //         [ 5, 6 ]
    }

    static void Print(dynamic array)
    {
        if (array.Length == 0)
            return;

        if (array[0].GetType().IsArray)
        {
            foreach (var element in array)
            {
                Print(element);
            }
        }
        else
        {
            int size = array.Length;
            string str = "[ ";

            for (int i = 0; i < size; i++)
            {
                str += array[i].ToString();

                if (i < size - 1)
                    str += ", ";
            }

            str += " ]";

            Console.WriteLine(str);
        }
    }

If you only want to test smaller part of codes - I suggest using LinqPad where you have AnyType.Dump() method and you mustn't implement anything ;)

You should provide 2 overloads of your Print method - you are free to call the 1D version from the 2D version as you want:

static void Print<T>(T[][] array)
{
     Console.WriteLine("Print 2D Array");
}
static void Print<T>(T[] array)
{
     Console.WriteLine("Print 1D Array");
}

Live example: http://rextester.com/LYBUN44476

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!