Creating a generic method in C#

后端 未结 6 1230
耶瑟儿~
耶瑟儿~ 2020-12-04 09:45

I am trying to combine a bunch of similar methods into a generic method. I have several methods that return the value of a querystring, or null if that querystring does not

6条回答
  •  失恋的感觉
    2020-12-04 09:54

    What about this? Change the return type from T to Nullable

    public static Nullable GetQueryString(string key) where T : struct, IConvertible
            {
                T result = default(T);
    
                if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
                {
                    string value = HttpContext.Current.Request.QueryString[key];
    
                    try
                    {
                        result = (T)Convert.ChangeType(value, typeof(T));  
                    }
                    catch
                    {
                        //Could not convert.  Pass back default value...
                        result = default(T);
                    }
                }
    
                return result;
            }
    

提交回复
热议问题