c# - 遍历对象的属性并获取 DateTime 类型属性的值

标签 c# .net reflection

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

最佳答案

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

关于c# - 遍历对象的属性并获取 DateTime 类型属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36656177/

相关文章:

c# - Entity Framework 核心 : Get changes occured in entity and related data

c# - VS 设计时错误 - 类型 'ICustomType[]' 的对象无法转换为类型 'ICustomType[]'

c# - 使 Stream 可搜索的 Stream 包装器?

c# - 使用反射比较对象属性

Java:实例化抽象类的特定子类的方法

c# - 命令模式 : Executing multiple commands in sequence

c# - 除非我打印一个值,否则发布和 Debug模式会给出不同的结果

c# - 防止几乎相同接口(interface)的代码重复

.net - XML 路径 - 不区分大小写

java - 如何从这个循环中提取反射?