【发布时间】:2019-04-09 19:08:21
【问题描述】:
我有一个打印多维矩阵的对象,例如:
namespace example;
Public class Object()
{
int lines, cols;
int matrix[,];
public Object(int lines, int cols)
{
this.lines = lines;
this.cols = cols;
matrix = new int[lines,cols];
PrintMatrix()
}
public void PrintMatrix()
{
Random rand = new Random();
Console.WriteLine();
for(int i = 0; i < lines ;i++)
for(int j = 0, j < cols; j++)
matrix[i,j]= rand.nextInt(1,10);
Console.WriteLine(matrix[i,j));
}
}
我想在控制台输出中打印如下内容:
matrix 1:
1 2 3
4 2 4
3 3 1
matrix 2:
2 3 4 4
1 1 2 2
3 3 4 4
1 1 8 8
matix 3:
...
所以我尝试在 List 或 Arraylist 中插入 Object:
static void Main(string[] args)
{
List<Object> conteiner = new List<Object>();
Object foo = new Object(3,3);
Object anotherFoo = new Object(4,4);
conteiner.add(foo);
conteiner.add(anotherFoo);
foreach(object item in conteiner)
{
console.WriteLine(item)
}
}
打印出来:
example.Object.foo;
example.Object.anotherFoo;
而不是多维数组。 我做错了什么,我该如何改进这个解决方案?
【问题讨论】:
-
Public class Object()根本不应该编译 -
Console.WriteLine(item.PrintMatrix()) ?
-
@DmitryS 你不能把它传递给 void..
-
已使用通用名称创建了类和方法以解释情况,无论如何感谢提示。
-
foreach(容器中的对象项) { item.PrintMatrix(); }
标签: c# arrays list arraylist multidimensional-array