C# 检查属性是否为类型或类型';s可空类型
我当前正在检查属性类型是DateTime还是可为空的DateTime,如下所示:C# 检查属性是否为类型或类型';s可空类型,c#,reflection,C#,Reflection,我当前正在检查属性类型是DateTime还是可为空的DateTime,如下所示: if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)) 有谁能告诉我,我是否可以通过检查底层类型将其压缩为一条语句?您可以尝试以下方法: if (prop.PropertyType.UnderlyingSystemType==typeof(DateTime)) …试试这样的东西 public cla
if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
有谁能告诉我,我是否可以通过检查底层类型将其压缩为一条语句?您可以尝试以下方法:
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; }
}
}
公共类程序
{
公共静态void Main(字符串[]args)
{
//你的密码在这里
DateTime?nullableDate=null;
bool output=CheckNull.IsNullable(nullableDate);//false
控制台写入线(输出);
}
公共静态类CheckNull
{
公共静态bool可为空(T){return false;}
公共静态bool为空(T?T),其中T:struct{return true;}
}
}
输出:
True
这里有一个简单的解决方案:typeof(DateTime?).IsAssignableFrom(prop.PropertyType)
。对于DateTime?
或DateTime
而言,这将是true;对于其他人而言,这将是false。请查看。回答您的问题。谢谢Mohammad,但不幸的是,这并没有拾取可空结构tanks Vasily,尽管我想确定它是DateTime还是DateTime?“我不想知道它是否可以为空。”卡梅隆前锋,我现在明白了。你能检查一下新版本吗?