为了检查是否Type
( propertyType
) 可以为空,我正在使用:
bool isNullable = "Nullable`1".Equals(propertyType.Name)
有什么方法可以避免使用魔术字符串吗?
绝对-使用Nullable.GetUnderlyingType http://msdn.microsoft.com/en-us/library/system.nullable.getunderlyingtype.aspx:
if (Nullable.GetUnderlyingType(propertyType) != null)
{
// It's nullable
}
请注意,这使用非泛型静态类System.Nullable http://msdn.microsoft.com/en-us/library/fs5xdbk8.aspx而不是通用结构Nullable<T>
.
另请注意,这将检查它是否代表specific(已关闭)可空值类型...如果您在generic类型,例如
public class Foo<T> where T : struct
{
public Nullable<T> Bar { get; set; }
}
Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)