简体   繁体   中英

How to read Object list item in C#

I have a object that prints a multidimensional matrix, eg:

 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));
        }

    }

i want to print in console output something like this:

    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:
 ...

So i have tried to insert the Object inside of List or Arraylist:

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)
     }   
 }

it prints :

 example.Object.foo;
 example.Object.anotherFoo;

instead of multidimentional arrays. What I´m doing wrong and how can i improve this solution?

If you want you could override the default ToString() method of your object.

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

Of course this forces you to make PrintMatrix() return a string but I would suggest to do it that way as it makes for better because more reusable code.

I would write something like the following :

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;
}

By the way if you're wondering why your numbers are't random try creating only one Random object. You can then use it as you're doing now.

Cause you are printing the type itself which calls it's default ToString() instead you should do call PrintMatrix() on every object instance. As well consider giving a better name to your type than Object since that's a built-in type

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

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