Generic Parse Method without Boxing

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

    Am I too late?

    static Dictionary table = 
        new Dictionary{
            { typeof(int), (Func)Int32.Parse },
            { typeof(double), (Func)Double.Parse },
            // ... as many as you want
        };
    
    static T Parse(string str)
    {
        if (!table.TryGet(typeof(T), out Delegate func))
            throw new ArgumentException();
        var typedFunc = (Func)func;
        return typedFunc(str);
    }
    

    When in trouble with types, try delegates and dicts!

提交回复
热议问题