vendredi 20 mai 2016

Display full name of all properties of an object

I have two class :

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime Date { get; set; }

    public bool isActif { get; set; }

    public Quantity Quantity { get; set; }
}

public class Quantity
{
    public string Color { get; set; }

    public int Number { get; set; }
}

And one method who display all properties of one instance of my class Customer with Reflection and Recursion :

public static void DisplayProperties(object objectA)
{
    if (objectA != null)
    {
        Type objectType;

        objectType = objectA.GetType();

        foreach (PropertyInfo propertyInfo in objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.CanRead))
        {
            object valueA = propertyInfo.GetValue(objectA, null);

            if (typeof(IComparable).IsAssignableFrom(propertyInfo.PropertyType) || propertyInfo.PropertyType.IsPrimitive || propertyInfo.PropertyType.IsValueType)
            {
                Console.WriteLine(propertyInfo.ReflectedType.Name + "." + propertyInfo.Name);
            }
            else
                DisplayProperties(valueA);
        }
    }
}

The result :

Customer.FirstName
Customer.LastName
Customer.Date
Customer.isActif
Quantity.Color
Quantity.Number

But I want to recover the full name of property like that

Customer.FirstName
Customer.LastName
Customer.Date
Customer.isActif
Customer.Quantity.Color
Customer.Quantity.Number

How to do ?





Aucun commentaire:

Enregistrer un commentaire