C# 检查类型是否为 Nullable 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8939939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to check if a type is Nullable
提问by Felice Pollano
In order to check if a Type( propertyType) is nullable, I'm using:
为了检查 a Type( propertyType) 是否可以为空,我使用:
bool isNullable = "Nullable`1".Equals(propertyType.Name)
Is there some way that avoid using magic strings ?
有什么方法可以避免使用魔法字符串吗?
采纳答案by Jon Skeet
Absolutely - use Nullable.GetUnderlyingType:
绝对 - 使用Nullable.GetUnderlyingType:
if (Nullable.GetUnderlyingType(propertyType) != null)
{
// It's nullable
}
Note that this uses the non-generic static class System.Nullablerather than the generic struct Nullable<T>.
请注意,这使用非泛型静态类System.Nullable而不是泛型 struct Nullable<T>。
Also note that that will check whether it represents a specific(closed) nullable value type... it won't work if you use it on a generictype, e.g.
另请注意,这将检查它是否代表特定的(封闭的)可为空值类型......如果您在泛型类型上使用它,它将不起作用,例如
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...
回答by VS1
Use the following code to determine whether a Type object represents a Nullable type. Remember that this code always returns false if the Type object was returned from a call to GetType.
使用以下代码确定 Type 对象是否表示 Nullable 类型。请记住,如果 Type 对象是从 GetType 调用返回的,则此代码始终返回 false。
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}
explained at the below MSDN link:
在下面的 MSDN 链接中解释:
http://msdn.microsoft.com/en-us/library/ms366789.aspx
http://msdn.microsoft.com/en-us/library/ms366789.aspx
Moreover, there is a similar discussion at this SO QA:
此外,在这个 SO QA 上也有类似的讨论:

