[英]Check if property is either of type or it's nullable type
我目前正在檢查屬性類型是DateTime還是可為null的DateTime,如下所示:
if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
誰能告訴我是否可以通過檢查基礎類型將其濃縮為一個語句?
這是一個簡單的解決方案: typeof(DateTime?).IsAssignableFrom(prop.PropertyType)
。 DateTime?
時間是否正確 DateTime?
或DateTime
,其他則為false 。
您可以嘗試以下方法:
if (prop.PropertyType.UnderlyingSystemType==typeof(DateTime))
...
試試這個
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.