Generic Parse Method without Boxing

前端 未结 8 1309
余生分开走
余生分开走 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条回答
  •  旧时难觅i
    2021-02-05 17:30

    For better readability, you could use a generic dictionary with an anonymous function as follows:

    var parserFuncs = new Dictionary>() {
        { typeof(int), p => (int) int.Parse(p) },
        { typeof(bool), p => (bool) bool.Parse(p) },
        { typeof(long), p => (long) long.Parse(p) },
        { typeof(short), p => (short) short.Parse(p) },
        { typeof(DateTime), p => (DateTime) DateTime.Parse(p) }
        /* ...same for all the other primitive types */
    };
    
    return (T) parserFuncs[typeof(T)](value);
    

提交回复
热议问题