2014-10-06 110 views
2

我想通過對象中的所有屬性進行循環,包括嵌套對象和集合中的對象,以檢查屬性是否爲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 ...... 

回答

2

這不是一個完整的答案,但我會從這裏開始。

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

這裏的關鍵是'財產.PropertyType.IsClass'。 if(property.PropertyType!= typeof(string)&& typeof(IEnumerable).IsAssignableFrom(property.PropertyType)){}'也被添加來迎合集合。謝謝 – 2014-10-07 07:20:09

0

檢查和的myType如果IsClass是真實的,然後遍歷了進去。你可能會想要做這個遞歸。

0

我認爲這是遠從原來的問題,但ReadPropertiesRecursive以上下降無限循環的

class Chain { public Chain Next { get; set; } } 

我寧願建議版本積累

private static void ReadPropertiesRecursive(Type type, IEnumerable<Type> visited) 
{ 
    foreach (PropertyInfo property in type.GetProperties()) 
    { 
     if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?)) 
     { 
      Console.WriteLine("test"); 
     } 
     else if (property.PropertyType.IsClass && !visited.Contains(property.PropertyType)) 
     { 
      ReadPropertiesRecursive(property.PropertyType, visited.Union(new Type[] { property.PropertyType })); 
     } 
    } 
}