如何遍历对象的嵌套属性

时间:2014-10-06 16:13:13

标签: c# .net

我试图遍历对象中的所有属性,包括嵌套对象和集合中的对象,以检查属性是否属于DateTime数据类型。如果是,则将值转换为UTC时间,使所有内容保持不变,包括其他属性的结构和值不变。 我的课程结构如下:

public class Custom1 {
    public int Id { get; set; }
    public DateTime? ExpiryDate { get; set; }
    public string Remark { get; set; }
    public Custom2 obj2 { get; set; }
}

public class Custom2 {
    public int Id { get; set; }
    public string Name { get; set; }
    public Custom3 obj3 { get; set; }
}

public class Custom3 {
    public int Id { get; set; }
    public DateTime DOB { get; set; }
    public IEnumerable<Custom1> obj1Collection { get; set; }
}

public static void Main() {
    Custom1 obj1 = GetCopyFromRepository<Custom1>();

    // this only loops through the properties of Custom1 but doesn't go into properties in Custom2 and Custom3
    var myType = typeof(Custom1);
    foreach (var property in myType.GetProperties()) {
        // ...
    }
}

如何循环浏览 obj1 中的属性并进一步向下遍历 obj2 然后 obj3 然后 obj1Collection ?该函数必须足够通用,因为传递给函数的Type无法在设计/编译时确定。应避免使用条件语句来测试类型,因为它们可能是类 Custom100

//avoid conditional statements like this
if (obj is Custom1) {
    //do something
} else if (obj is Custom2) {
    //do something else
}  else if (obj is Custom3) {
    //do something else
} else if ......

3 个答案:

答案 0 :(得分:3)

这不是一个完整的答案,但我会从这里开始。

var myType = typeof(Custom1);
            ReadPropertiesRecursive(myType);


private static void ReadPropertiesRecursive(Type type)
        {
            foreach (PropertyInfo property in type.GetProperties())
            {
                if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
                {
                    Console.WriteLine("test");
                }
                if (property.PropertyType.IsClass)
                {
                    ReadPropertiesRecursive(property.PropertyType);
                }
            }
        }

答案 1 :(得分:0)

检查myType,如果IsClass为true,则遍历它。你可能想要这个递归。

答案 2 :(得分:0)

我认为这与原始问题相去甚远,但上面的ReadPropertiesRecursive落在

上的无限循环中
class Chain { public Chain Next { get; set; } }

我宁愿建议带累积的版本

private static void ReadPropertiesRecursive(Type type, IEnumerable<Type> visited)
{
    foreach (PropertyInfo property in type.GetProperties())
    {
        if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
        {
            Console.WriteLine("test");
        }
        else if (property.PropertyType.IsClass && !visited.Contains(property.PropertyType))
        {
            ReadPropertiesRecursive(property.PropertyType, visited.Union(new Type[] { property.PropertyType }));
        }
    }
}