2016-04-15 71 views
2

我有一個對象列表(汽車)。對於列表中的每輛車,我需要遍歷它並找到任何類型的DateTime屬性。如果我找到DateTime屬性,我需要獲取該值並進行時間轉換。現在只需將DateTime屬性值打印到控制檯。我有問題了解我需要在prop.GetValue函數的第一個參數中放置什麼。任何幫助,將不勝感激!遍歷對象的屬性並獲取DateTime類型的值

foreach (var car in carList) 
{ 
    foreach (PropertyInfo car in car.GetType().GetProperties()) 
    { 
     var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; 
     if (type == typeof (DateTime)) 
     { 
      Console.WriteLine(prop.GetValue(???, null).ToString()); 
     } 
    } 
} 
+2

認沽'car'有 – Quantic

回答

4

您需要使用car作爲第一個參數:

foreach (var car in carList) 
{ 
    foreach (PropertyInfo prop in car.GetType().GetProperties()) 
    { 
     var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; 
     if (type == typeof (DateTime)) 
     { 
      Console.WriteLine(prop.GetValue(car, null).ToString()); 
     } 
    } 
} 
相關問題