如何遍历对象的嵌套属性

Twi*_*per 5 .net c#

我试图遍历对象中的所有属性,包括嵌套对象和集合中的对象,以检查该属性是否为 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()) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如何通过属性我环路OBJ1和导线的进一步下跌OBJ2,然后OBJ 3然后obj1Collection?该函数必须足够通用,因为在设计/编译时无法确定传递给函数的类型。应该避免测试类型的条件语句,因为它们可能是类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 ......
Run Code Online (Sandbox Code Playgroud)

Sun*_*nny 6

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

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);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 这里的关键是`property.PropertyType.IsClass`。`if (property.PropertyType != typeof(string) &amp;&amp; typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) {}` 也被添加来满足集合。谢谢 (2认同)