Know the type of object and its properties from Listobject

2

I have a method that receives a list of objects:

private void escribe(List<object> lista)

that a priori I do not know what class they are and I want to know at the time of execution the properties of each of the objects within the list.

I've tried with:

        Type type = lista.GetType();            
        var PropertyInfos = lista.GetType().GetProperties();

I've also tried with:

        Type tip = lista.GetType();
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
             var itemType = type.GetGenericArguments()[0];
        }

But I can not recover the properties of the object in question. Greetings and thanks for the help.

Edit: I add information about the class I'm tested with, although I really want it to work for anyone.

 public class Prueba
{
    string prop1;
    int prop2;
    bool prop3;
    float prop4;
    //List<string> prop5;
    object prop6;}

And all these fields are transformed into properties with the first letter in capital letters

    
asked by U. Busto 03.08.2017 в 11:46
source

2 answers

2

The problem you have is that you are getting the type of List (which will always be of type List , when you want to get the type of object within that list, to obtain its properties.

Let's imagine this example. We have a test class:

class Ejemplo
{
    public int pos1 { get; set; }
    public int pos2 { get; set; }
    public int pos3 { get; set; }
}

Now we define your list List<object> and add an object of type Ejemplo :

List<object> lista = new List<object>();

lista.Add(new Ejemplo() { pos1 = 1, pos2 = 2, pos3 = 3 });
var PropertyInfos = lista.First().GetType().GetProperties();
foreach (var prop in PropertyInfos)
{
     //aqui recorremos las propiedades
}

Notice that I use First to access the first item in the list, and from it I get the type first and then its properties.

    
answered by 03.08.2017 / 12:08
source
2

The problem you have is that you are accessing the properties of List<object> and what I want to imagine is that you need to access the properties of the object itself.
If so, you have to go through them and get the type of the specific object and not the one on the list

private void escribe(List<object> lista)
{
    foreach( object objItem in lista)
    {
        Type type = objItem.GetType();    
        //Aquí tendrás als propiedades del objeto actual        
        var PropertyInfos = lista.GetType().GetProperties();

    }   
}
    
answered by 03.08.2017 в 12:05