[英]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.