简体   繁体   English

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

[英]Check if property is either of type or it's nullable type

I am currently checking if a property type is either a DateTime or a nullable DateTime like this: 我目前正在检查属性类型是DateTime还是可为null的DateTime,如下所示:

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

Can anyone please tell me if I can somehow condense this into a single statement by checking the underlying type? 谁能告诉我是否可以通过检查基础类型将其浓缩为一个语句?

Here is a simple sollution: typeof(DateTime?).IsAssignableFrom(prop.PropertyType) . 这是一个简单的解决方案: typeof(DateTime?).IsAssignableFrom(prop.PropertyType) This will be true for DateTime? DateTime?时间是否正确 DateTime? or DateTime and false for others. DateTime ,其他则为false

You may try this: 您可以尝试以下方法:

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

... ...

Try something like this 试试这个

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; }
 }
}

output : True 输出: True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查实体框架类型的属性是否可为空 - How to check if a property of an Entity Framework type is Nullable 使用LINQ检查可为空的类型 - Check nullable type with LINQ 强制转换为值类型&#39;Enum&#39;失败,因为实例化值为null。 结果类型的参数或查询必须使用可为空的类型 - Cast to value type 'Enum' failed as the materialized value is null. Either the result type's param or query must use nullable type 可空类型不是可空类型吗? - Nullable type is not a nullable type? 如何检查 Type 是否为可为空的系统类型 - How to check if Type is a nullable system type 实体类型 &#39;xxx&#39; 上的属性 &#39;xxx&#39; 不能标记为可空/可选,因为该属性的类型是 &#39;short&#39;,它不是可空类型 - The property 'xxx' on entity type 'xxx' cannot be marked as nullable/optional because the type of the property is 'short' which is not a nullable type 满足或静音可为空的泛型类型属性警告 - Satisfy or silence nullable generic type property warning 动态Lambda表达式(OrderBy)和可为空的属性类型 - Dynamic lambda expression (OrderBy) and nullable property type 如何检测与可为空属性相结合的数据类型 - How to detect data type combined with nullable property 如何从可为空的类型获取属性? - How to get property from a nullable type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM