我想通過對象中的所有屬性進行循環,包括嵌套對象和集合中的對象,以檢查屬性是否爲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的然後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 ......
這裏的關鍵是'財產.PropertyType.IsClass'。 if(property.PropertyType!= typeof(string)&& typeof(IEnumerable).IsAssignableFrom(property.PropertyType)){}'也被添加來迎合集合。謝謝 – 2014-10-07 07:20:09