IsPrimitive不包含可空的原始值

Ran*_*dom 12 c# primitive types

我想检查Type是否是原始的,并使用以下代码:

return type.IsValueType && type.IsPrimitive;
Run Code Online (Sandbox Code Playgroud)

只要原语不可为空,这就可以正常工作.例如int ?,如何检查类型是否为可为空的原始类型?(仅供参考:type.IsPrimitive == false在int?)

ken*_*n2k 16

来自MSDN:

基元类型是布尔,字节,SByte,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single.

所以基本上你应该预料Nullable<Int32>不是一个原始类型.

你可以使用Nullable.GetUnderlyingType为"提取" Int32Nullable<Int32>.


Mik*_*oud 7

首先,你需要确定它是否Nullable<>然后你需要获取可空类型:

if (type.IsGenericType
    && type.GetGenericTypeDefinition() == typeof(Nullable<>)
    && type.GetGenericArguments().Any(t => t.IsValueType && t.IsPrimitive))
{
    // it's a nullable primitive
}
Run Code Online (Sandbox Code Playgroud)

现在,上述工作,但不是递归.为了让它以递归方式工作,你需要将它放入一个方法,你可以递归调用所有类型GetGenericArguments.但是,如果没有必要,请不要这样做.

该代码也可以转换为:

if (type.GetGenericArguments().Any(t => t.IsValueType && t.IsPrimitive))
{
    // it's a nullable primitive
}
Run Code Online (Sandbox Code Playgroud)

但需要注意的是,它可能是一个通用的引用类型,实际上可能无法满足您需要的原语定义.再次,请记住,前面提到的更简洁,但可能会返回误报.