c# - 如何遍历对象的嵌套属性

标签 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?该函数必须足够通用,因为传递给该函数的类型无法在设计/编译时确定。应避免使用条件语句来测试类型,因为它们可能是 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 ......

最佳答案

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

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

关于c# - 如何遍历对象的嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26220358/

相关文章:

c# - Draw() 20,000 32 x 32 纹理或 1 个大纹理 20,000 次

c# - 使用 ManualResetEvent 锁定测试对 NAudio 进行单元测试

c# - MediatR 仅使用 ASP.NET DI 在程序集中注册特定处理程序

.net - 在 .NET 中应用 XSLT 与 Notepad++ 的结果不同(不正确)

c# - [OptionalField] 和 [NonSerialized] 有什么区别

c# - 如何在 Dapper .Net 中使用 SQL 批量复制?

c# - 快速将整个MongoDB集合索引到Elastcticsearch

c# - "Enable Debugging of Unmanaged Code"在哪里可以在系统运行时编辑代码?

c# - 如何使用来自外部应用程序的 View

c# - 在 Windows 10 中检测到布局循环,但在 Windows 8.1 中未检测到