有两种可为null的类型-
Nullable<T>和引用类型。
乔恩(Jon)纠正了我的意见,即如果很难装箱,则可以键入文字,但是使用泛型则可以:-下面呢。这实际上是测试type
T,但是仅将
obj参数用于泛型类型推断(以使其易于调用)-
obj尽管没有参数,它的工作原理几乎相同。
static bool IsNullable<T>(T obj){ if (obj == null) return true; // obvious Type type = typeof(T); if (!type.IsValueType) return true; // ref-type if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T> return false; // value-type}但是,如果您已经将该值装箱到对象变量中,则此方法将无法很好地工作。
Microsoft文档:https : //docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/nullable-
types/how-to-identify-a-nullable-type



