convert int to nullable int?

前端 未结 6 791
北恋
北恋 2020-12-15 04:43

I need to know how to convert an int to a nullable int. However, I keep getting an error \"The binary operator Equal is not defined for the types \'System.Nullable`1[System.

6条回答
  •  情书的邮戳
    2020-12-15 05:24

    Here you go. A generic string to nullable primitive solution.

    int? n = "  99 ".ToNullable(); 
    
    /// 
    /// Developed by Taylor Love
    /// 
    public static class ToNullableStringExtension
    {
        /// 
        /// More convenient than using T.TryParse(string, out T). 
        /// Works with primitive types, structs, and enums.
        /// Tries to parse the string to an instance of the type specified.
        /// If the input cannot be parsed, null will be returned.
        /// 
        /// 
        /// If the value of the caller is null, null will be returned.
        /// So if you have "string s = null;" and then you try "s.ToNullable...",
        /// null will be returned. No null exception will be thrown. 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static T? ToNullable(this string p_self) where T : struct
        {
            if (!string.IsNullOrEmpty(p_self))
            {
                var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
                if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
                if (typeof(T).IsEnum) { T t; if (Enum.TryParse(p_self, out t)) return t;}
            }
    
            return null;
        }
    

    https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions

提交回复
热议问题