【问题标题】:How to read Object list item in C#如何在 C# 中读取对象列表项
【发布时间】: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


【解决方案1】:

如果您愿意,您可以覆盖对象的默认 ToString() 方法。

 public override string ToString()
 {
     return PrintMatrix();
 }

当然,这会迫使您让PrintMatrix() 返回一个字符串,但我建议您这样做,因为这样会更好,因为代码可重用性更高。

我会写如下内容:

public string PrintMatrix()
{
    string result = string.Empty;

    for(int i = 0; i < lines ;i++)
    {
        for(int j = 0, j < cols; j++)
        {
            matrix[i,j] = rand.Next(1,10);
            result += $"{matrix[i,j]} ";
        }
        result +=  Environment.NewLine ;
    }

    return result;
}

顺便说一下,如果您想知道为什么您的数字不是随机的,请尝试只创建一个 Random 对象。然后您就可以像现在一样使用它了。

【讨论】:

  • 谢谢你,听起来不错的建议,我会试试的。
【解决方案2】:

因为您正在打印类型本身,它调用它的默认 ToString(),而不是您应该在每个对象实例上调用 PrintMatrix()。同时考虑给你的类型起一个比Object更好的名字,因为这是一个内置类型

 foreach(Object item in conteiner)
 {
   item.PrintMatrix();
 }   

【讨论】:

  • 谢谢老哥,我试试看。
  • 但是方法返回void。只需拨打PrintMatrix,无需拨打Console.WriteLine
猜你喜欢
  • 2010-11-28
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 2012-07-17
  • 2017-06-16
相关资源
最近更新 更多