Generic Parse Method without Boxing

前端 未结 8 1293
余生分开走
余生分开走 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:34

    public static T Parse(this NameValueCollection col, string key)
    {
      return (T)Convert.ChangeType(col[key], typeof(T));
    }
    

    I'm not entirely sure of ChangeType boxes or not (I guess reading the docs would tell me, but I'm pressed for time right now), but at least it gets rid of all that type-checking. The boxing overhead is not very high, though, so I wouldn't worry too much about it. If you're worried about run-time type consistency, I'd write the function as:

    public static T Parse(this NameValueCollection col, string key)
    {
      T value;
    
      try
      {
        value = (T)Convert.ChangeType(col[key], typeof(T));
      }
      catch
      {
        value = default(T);
      }
    
      return value;
    }
    

    This way the function won't bomb if the value cannot be converted for whatever reason. That means, of course, that you'll have to check the returned value (which you'd have to do anyway since the user can edit the querystring).

提交回复
热议问题