【问题标题】:C# determine a Nullable property DateTime type when using reflectionC# 使用反射时确定 Nullable 属性 DateTime 类型
【发布时间】:2019-10-08 01:57:00
【问题描述】:

我有一个关于如何确定对象的 Nullable 属性类型的问题。

ObjectA 有一个属性DateTime? CreateDate;

当我像下面的代码那样遍历它的属性时,我如何检查一个属性是否是 Nullable DateTime 类型?

foreach (PropertyInfo pi in ObjectA.GetType().GetProperties())
{
    //do the compare here
}

【问题讨论】:

    标签: c# reflection nullable


    【解决方案1】:
    pi.PropertyType == typeof(DateTime?)
    

    【讨论】:

    • 你的另一个问题......我如何根据类型进行切换?我必须改用全名吗?还是应该改用“If”语句? Nullable DateTime 类型的字符串 FullName 是什么?谢谢
    • 我强烈建议您使用if,并避免使用FullName。如果你想在DateTime? 中看到FullName,那么只需打印出typeof(DateTime?).FullName - 但它会很长,会降低你的代码的可读性,很脆弱(如果你偶尔在某处删除一个字符怎么办?),并且将导致较慢的比较(Type 对象本身通过引用进行比较 - 即,对于任何给定,最多有一个 Type 对象,因此如果两个引用相等,则这是同一类型;并且这种比较很快)
    【解决方案2】:
    pi.PropertyType == typeof(Nullable<DateTime>);
    

    【讨论】:

      【解决方案3】:

      试试:

      property.PropertyType.Equals(typeof(DateTime?))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-10
        • 2010-12-11
        • 2012-01-22
        • 1970-01-01
        • 1970-01-01
        • 2018-06-05
        • 1970-01-01
        • 2017-04-24
        相关资源
        最近更新 更多