Switch case and generics checking

后端 未结 7 719
情话喂你
情话喂你 2021-01-01 10:36

I want to write a function that format int and decimal differently into string

I have this code:

and I want to rewrite it to generi

相关标签:
7条回答
  • 2021-01-01 10:58

    You could check the type of the variabele;

        public static string FormatWithCommaSeperator<T>(T value)
        {
            if (value is int)
            {
                // Do your int formatting here
            }
            else if (value is decimal)
            {
                // Do your decimal formatting here
            }
            return "Parameter 'value' is not an integer or decimal"; // Or throw an exception of some kind?
        }
    
    0 讨论(0)
  • 2021-01-01 11:01

    Edit: If you only want to handle exactly int and double, just have two overloads:

    DoFormat(int value)
    {
    }
    
    DoFormat(double value)
    {
    }
    

    If you insist on using generics:

    switch (value.GetType().Name)
    {
        case "Int32":
            break;
        case "Double":
            break;
        default:
            break;
    }
    

    OR

    if (value is int)
    {
        int iValue = (int)(object)value;
    }
    else if (value is double)
    {
        double dValue = (double)(object)value;
    }
    else
    {
    }
    
    0 讨论(0)
  • 2021-01-01 11:06

    Another way to do switch on generic is:

    switch (typeof(T))
    {
        case Type intType when intType == typeof(int):
            ...
        case Type decimalType when decimalType == typeof(decimal):
            ...
        default:
            ...
    }
    
    0 讨论(0)
  • 2021-01-01 11:08

    In modern C#:

    public static string FormatWithCommaSeperator<T>(T value) where T : struct
    {
        switch (value)
        {
            case int i:
                return $"integer {i}";
            case double d:
                return $"double {d}";
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:15

    Alternatively you could always do:

    public static string FormatWithCommaSeparator<T>(T[] items)
    {
        var itemArray = items.Select(i => i.ToString());
    
        return string.Join(", ", itemArray);
    }
    
    0 讨论(0)
  • 2021-01-01 11:17

    You could instead of using generics use IConvertible

        public static string FormatWithCommaSeperator(IConvertible value)
        {
                IConvertible convertable = value as IConvertible;
                if(value is int)
                {
                    int iValue = convertable.ToInt32(null);
                    //Return with format.
                }
                .....
        }
    
    0 讨论(0)
提交回复
热议问题