如何遍历对象的嵌套属性 [英] How to iterate through nested properties of an object

查看:81
本文介绍了如何遍历对象的嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to loop through all properties in an object including nested objects and objects in collections, to check if the property is of DateTime data type. If it is, convert the value to UTC time leaving everything intact including the structure and the value of other properties untouched. The structure of my classes as follows:

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

How do I loop through the properties in obj1 and traverse further down obj2 then obj3 then obj1Collection? The function have to be generic enough because the Type passed to the function cannot be determined at design/compile time. Conditional statements to test for Types should be avoided since they might be class 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 ......

推荐答案

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

This is not a complete answer but I would start from here.

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

这篇关于如何遍历对象的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆