mardi 10 janvier 2017

How can I list all properties using reflection

class structure

public class Cat
{
    public string Color { get; set; }
    public int Speed { get; set; }
    public string saying { get; set; }
    public Foods foods { get; set; }
}

public class Foods
{
    public List<Food> food { get; set; }
}

public class Food
{
    public string Name { get; set; }
    public bool Sweet { get; set; }
}

And initialization

var aCat = new Cat
{
    Color = "red",
    Speed = 10,
    saying = "i'm a @cat",
    foods = new Foods
    {
        food = new List<Food>
        {
            new Food
            {
                Name="num1",
                Sweet=false
            },
            new Food
            {
                Name="num2",
                Sweet=true
            }
        }
    }
};

Now,I wanna foreah the Cat to list all name and value of properties.

Type t = aCat.GetType();

foreach(var item in t.GetProperties())
{
    Console.WriteLine("{0} = {1}", item.Name, item.GetValue(aCat));                    
}

But,the foods is a class,the foods property value is class type, I don't wanna write something looks like

if(item.GetValue(aCat) is Foods)

How can I do something like..

you are my custom class ,you have property and lenght is bigger than 0
well,another foreach turn.

thanks bro





Aucun commentaire:

Enregistrer un commentaire