2016-04-15 67 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()); 
     } 
    } 
} 
相关问题