遍历对象的属性并获取类型为DateTime的值

92

我有一个对象列表(汽车)。对于列表中的每辆汽车,我需要循环遍历并查找任何 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());
        }
    }
}
1个回答

155

您需要将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());
         }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接