Switch case and generics checking

后端 未结 7 718
情话喂你
情话喂你 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 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
    {
    }
    

提交回复
热议问题