Generic Parse Method without Boxing

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

    I'll add a little undocumented way:

    public static T Convert()
    {
        if (typeof(T) == typeof(int))
        {
            int a = 5;
            T value = __refvalue(__makeref(a), T);
            return value;
        }
        else if (typeof(T) == typeof(long))
        {
            long a = 6;
            T value = __refvalue(__makeref(a), T);
            return value;
        }
    
        throw new NotImplementedException();
    }
    

    There is little documentation about them, but they work as of C# 4.0. Read for example here Hidden Features of C#? Remember that undocumented means unsupported, blah blah blah could not work in the future blah blah blah if you use them the devil will come for you blah blah blah :-)

提交回复
热议问题