I am currently working with lots of arrays and for debugging purposes I wrote a generic Print()
method to print different kinds of arrays
static void Main()
{
Print(new double[]{ 1, 2, 3 });
// Output: [ 1, 2, 3 ]
}
static void Print<T>(T[] array)
{
int size = array.Length;
if (size == 0)
return;
string str = "[ ";
for (int i = 0; i < size; i++)
{
str += array[i].ToString();
if (i < size - 1)
str += ", ";
}
str += " ]";
Console.WriteLine(str);
}
which works fine so far. Then I wanted to print an array of arrays, like double[][]
, and tried the following:
static 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<T>(T[] array)
{
if (array.Length == 0)
return;
if (array[0].GetType().IsArray)
{
foreach (var element in array)
{
Print<T>(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);
}
}
I just wanted to check if the elements of array
again are arrays, and if so, I call the function Print again for each element
of array
. But Print(element)
doesn't work, since element
is of type T
and not T[]
and I don't know how to tell the compiler that in this case T
is an array. What do I have to do to make this work?
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
来源:https://stackoverflow.com/questions/45415554/generic-printing-of-jagged-arrays