我试图遍历对象中的所有属性,包括嵌套对象和集合中的对象,以检查属性是否为 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/