在stack overflow看到一个问答
How to check if an object is nullable?
我无法在上面发表评论,因为我没有超过 50 条评论,这就是我在这里提问的原因。
if(Nullable.GetUnderlyingType(myType) !=null)
{
// It's Nullable
}
如果 myType 是 system.string
Nullable.GetUnderlyingType(myType)
返回空值
我认为 System.string 可以为空!
来电Nullable.GetUnderlyingType()
不会为 typeof(string)
返回任何有意义的信息. documentation提及:
Returns the underlying type argument of the specified nullable type.
Return Value
The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null.
换句话说,如果您实际传递给它一个实现了 Nullable<T>
的类型,它只会返回有用的东西。 ,例如 int?
, bool?
, 等等。 这就是这里“可空类型”的意思。
您还可以在 Marc's answer to the question you link to 的代码中看到它的预期用途:
static bool IsNullable<T>(T obj)
{
// ...
if (!type.IsValueType) return true; // ref-type
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
}