Rob*_*van 4 c# nullable value-type
要检查值类型是否可为空,我现在正在执行以下操作:
int? i = null;
bool isNullable = i.GetType().ToString().Contains("System.Nullable");
Run Code Online (Sandbox Code Playgroud)
有没有更优雅的方式来做到这一点?
Jon*_*eet 14
您可以使用Nullable.GetUnderlyingType(Type)- null如果它不是可以开头的可空类型,则返回,否则返回基础值类型:
if (Nullable.GetUnderlyingType(t) != null)
{
// Yup, t is a nullable value type
}
Run Code Online (Sandbox Code Playgroud)
请注意,这使用Nullable静态类,而不是Nullable<T>结构.
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// it is a nullable type
}
Run Code Online (Sandbox Code Playgroud)
这就是Microsoft建议您识别可空类型的方式