How do I convert a System.Type to its nullable version?

前端 未结 4 1391
长发绾君心
长发绾君心 2021-01-30 19:21

Once again one of those: \"Is there an easier built-in way of doing things instead of my helper method?\"

So it\'s easy to get the underlying type from a nullable type,

4条回答
  •  既然无缘
    2021-01-30 19:59

    Lyman's answer is great and has helped me, however, there's one more bug which needs to be fixed.

    Nullable.GetUnderlyingType(type) should only be called iff the type isn't already a Nullable type. Otherwise, it seems to erroneously return null when the type derives from System.RuntimeType (such as when I pass in typeof(System.Int32) ). The below version avoids needing to call Nullable.GetUnderlyingType(type) by checking if the type is Nullable instead.

    Below you'll find an ExtensionMethod version of this method which will immediately return the type unless it's a ValueType that's not already Nullable.

    Type NullableVersion(this Type sourceType)
    {
        if(sourceType == null)
        {
            // Throw System.ArgumentNullException or return null, your preference
        }
        else if(sourceType == typeof(void))
        { // Special Handling - known cases where Exceptions would be thrown
            return null; // There is no Nullable version of void
        }
    
        return !sourceType.IsValueType
                || (sourceType.IsGenericType
                   && sourceType.GetGenericTypeDefinition() == typeof(Nullable<>) )
            ? sourceType
            : typeof(Nullable<>).MakeGenericType(sourceType);
    }
    

    (I'm sorry, but I couldn't simply post a comment to Lyman's answer because I was new and didn't have enough rep yet.)

提交回复
热议问题