简体   繁体   中英

How can i get the values of each object in List

I'm building a project for my degree (for my school degree) and i've builded a list, a generic list to add objects and to work with them.

Hapeens that i also create inside my list class a new method to List the contents of list for all <T> objects

I would like to print each <T> parameter or value, for example if <T> is <Cars> i want to print Mark, Model, Year, Fuel, Color ...

I know also that is throught a propriety, and try to build a propriety to solve this, but, may something could be wrong in my code:

Inside my List classe i have this:

  • an T [] array;
  • Constructors

    //Constructores

    public GenericList() { myList = new T[MAXLENGTH]; counter = 0; }

and more two methods to add, list, and also a propriety of T[] array :

 public T[] ObjectosEmLista
        {
            get { return myList; }
            set { myList = value; }
        }

        //public T ConsultaObjectoPorNome(string n)
        //{

        //}

        public T AddObject (T obj)
        {
            aux.Add(obj);
            return obj;
        }





        //Listagem
        public void List()
        {

            foreach (T t in myList)
            {
                Console.WriteLine("Marca {0} ", t);
            }


        }

And in main Class:

  GenericList<Auto> autos = new GenericList<Auto>();
  autos.AddObject(new Auto("89-FF-42", "Citroen", "C4 1.6HDI"));
  autos.AddObject(new Auto("19-89-LH", "Mercedes", "E230"));
  autos.AddObject(new Auto("75-FA-45", "Skoda", "Fabia"));

So, how i can print for each one, the plate mark and model. Please help me, it's important.

I think what you are looking for is Reflection . Try this to get information about fields in your class.

FieldInfo[] fields = data.GetType().GetFields(BindingFlags.Public | 
                                              BindingFlags.NonPublic | 
                                              BindingFlags.Instance);

From this point it is easy to extract further data (use .GetValue() on a field).

foreach (var element in array)
    foreach (var field in fields)
        Console.WriteLine(field.Name + ": " + field.GetValue(element));

You could try a Foreach loop

foreach (Auto item in autos)
{
   /// here you will get every item in the list and can access item.properties
   print item.ModelName //, .each property.. 
   //or
   print item.ToString;
}

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