我有一个对象列表(汽车)。对于列表中的每辆车,我需要遍历它并找到DateTime
类型的任何属性。如果我找到DateTime
的属性,我需要获取值并进行时间转换。现在,我们只需将DateTime
属性值打印到控制台即可。我在理解我需要放在prop.GetValue
函数的第一个参数中时遇到问题。任何帮助,将不胜感激!
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());
}
}
}
答案 0 :(得分:16)
您需要使用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());
}
}
}