【问题标题】:Loop through an object's properties and get the values for those of type DateTime循环遍历对象的属性并获取 DateTime 类型的值
【发布时间】:2016-04-15 20:22:30
【问题描述】:

我有一个对象列表(汽车)。对于列表中的每辆车,我需要遍历它并找到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());
        }
    }
}

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

    你需要使用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());
             }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-19
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2021-11-20
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多