代码之家  ›  专栏  ›  技术社区  ›  Cameron Forward

检查属性是属于类型还是可为空类型

  •  0
  • Cameron Forward  · 技术社区  · 6 年前

    if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
    

    有人能告诉我是否可以通过检查底层类型将其压缩成一个语句吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   vasily.sib    6 年前

    下面是一个简单的解决方案: typeof(DateTime?).IsAssignableFrom(prop.PropertyType) . 这将是 真的 对于 DateTime? DateTime

        2
  •  0
  •   Mohammad Nikravesh    6 年前

    你可以试试这个:

    if (prop.PropertyType.UnderlyingSystemType==typeof(DateTime))
    

    ...

        3
  •  0
  •   Saif    6 年前

    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
             DateTime? nullableDate = null;
    
             bool output = CheckNull.IsNullable(nullableDate); // false
    
             Console.WriteLine(output );
        }
    
     public static class CheckNull
     {
       public static bool IsNullable<T>(T t) { return false; }
       public static bool IsNullable<T>(T? t) where T : struct { return true; }
     }
    }
    

    输出: True