如果我有Type
,是否有一些简单的方法可以使用Reflection来表示它代表可为空的值类型?理想情况是比以下方法更干净(并且更正确)的东西:
static bool IsNullable(Type type)
{
return type.IsValueType && type.Name.StartsWith("Nullable");
}
最佳答案
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)
您可能还会发现
Nullable.GetUnderlyingType(Type nullableType)
有用,可以轻松获取传入的T
的typeof(Nullable<T>)
。
关于.net - 如何使用反射判断对象的类型是否为Nullable <T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3865021/