Generic Parse Method without Boxing

前端 未结 8 1304
余生分开走
余生分开走 2021-02-05 17:12

I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection. I tried two methods but both of these methods are goin

相关标签:
8条回答
  • 2021-02-05 17:53

    Another suggestion for implementation, using a TryParse or Parse method with a generic approach. I wrote this originally to convert strings parsed from a csv file into different types, int, decimal, list, etc.

     public static bool TryParse<T>(this string value, out T newValue, T defaultValue = default(T))
            where T : struct, IConvertible
        {
            newValue = defaultValue;
            try
            {
                newValue = (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                return false;
            }
            return true;
        }
    
        public static T Parse<T>(this string value)
            where T : struct, IConvertible
        {
            return (T) Convert.ChangeType(value, typeof (T));
        }
    

    Here, the try parse method first sets the newValue to the default value, then tries to convert value to type T and return the newValue as type T. If the conversion fails, it returns the default value of T.

    The Parse method, simply tries to do the conversion, however if its not fail safe and will throw an exception if the conversion fails.

    0 讨论(0)
  • 2021-02-05 17:53
    int value = int.Parse(Request.QueryString["RecordID"]);
    
    0 讨论(0)
提交回复
热议问题