显示对象的所有属性的全名

时间:2016-05-20 19:06:57

标签: c# recursion reflection

我有两节课:

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

使用Reflection和Recursion显示我的类Customer的一个实例的所有属性的一个方法:

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

结果:

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

但我想恢复那个属性的全名

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

怎么办?

2 个答案:

答案 0 :(得分:0)

一个好的方法是在每次调用DisplayProperties时传递路径。

更改方法签名:

public static void DisplayProperties(object objectA, string path = "")

更改打印方法

Console.WriteLine("{0}{1}.{2}", path, propertyInfo.ReflectedType.Name, propertyInfo.Name);

更改递归调用方法

DisplayProperties(valueA, objectA.GetType().Name + ".");

答案 1 :(得分:0)

将您的DisplayProperties方法更改为此

public static void DisplayProperties(object objectA, string objName="")
{
    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(objName +  (objName==""? "" : ".") + propertyInfo.ReflectedType.Name + "." + propertyInfo.Name);
            }
            else
                DisplayProperties(valueA, objName + (objName == "" ? "" : ".") + objectType.Name);
        }
    }
}