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

前端 未结 4 1398
长发绾君心
长发绾君心 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 20:19

    Here is the code I use:

    Type GetNullableType(Type type) {
        // Use Nullable.GetUnderlyingType() to remove the Nullable wrapper if type is already nullable.
        type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
        if (type.IsValueType)
            return typeof(Nullable<>).MakeGenericType(type);
        else
            return type;
    }
    

提交回复
热议问题