c# – 循环访问对象的属性并获取DateTime类型的值

前端之家收集整理的这篇文章主要介绍了c# – 循环访问对象的属性并获取DateTime类型的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个对象列表(汽车).对于列表中的每辆车,我需要遍历它并找到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());
        }
    }
}

解决方法

你需要使用汽车作为第一个参数:
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());
         }
    }
}
原文链接:https://www.f2er.com/csharp/96625.html

猜你在找的C#相关文章