Fel*_*ano 162 c# generics nullable
为了检查a Type
(propertyType
)是否可以为空,我正在使用:
bool isNullable = "Nullable`1".Equals(propertyType.Name)
Run Code Online (Sandbox Code Playgroud)
有没有办法避免使用魔法字符串?
Jon*_*eet 330
绝对 - 使用Nullable.GetUnderlyingType
:
if (Nullable.GetUnderlyingType(propertyType) != null)
{
// It's nullable
}
Run Code Online (Sandbox Code Playgroud)
请注意,这使用非泛型静态类System.Nullable
而不是通用结构Nullable<T>
.
另请注意,这将检查它是否代表特定(已关闭)可为空的值类型...如果您在泛型类型上使用它将无法工作,例如
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...
Run Code Online (Sandbox Code Playgroud)
VS1*_*VS1 40
使用以下代码确定Type对象是否表示Nullable类型.请记住,如果从对GetType的调用返回Type对象,则此代码始终返回false.
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}
Run Code Online (Sandbox Code Playgroud)
在下面的MSDN链接中解释:
http://msdn.microsoft.com/en-us/library/ms366789.aspx
此外,在此SO QA上也有类似的讨论:
归档时间: |
|
查看次数: |
64861 次 |
最近记录: |