C# 切换大小写和泛型检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9802325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:55:57  来源:igfitidea点击:

Switch case and generics checking

c#generics

提问by Elad Benda

I want to write a function that format intand decimaldifferently into string

我想写一个函数,格式intdecimal不同的字符串

I have this code:

我有这个代码:

and I want to rewrite it to generics:

我想将其重写为泛型:

    public static string FormatAsIntWithCommaSeperator(int value)
    {
        if (value == 0 || (value > -1 && value < 1))
            return "0";
        return String.Format("{0:#,###,###}", value);
    }

    public static string FormatAsDecimalWithCommaSeperator(decimal value)
    {
        return String.Format("{0:#,###,###.##}", value);
    }


    public static string FormatWithCommaSeperator<T>(T value) where T : struct
    {
        string formattedString = string.Empty;

        if (typeof(T) == typeof(int))
        {
            if ((int)value == 0 || (value > -1 && value < 1))
            return "0";

            formattedString = String.Format("{0:#,###,###}", value);
        }

        //some code...
    }

    /// <summary>
    /// If the number is an int - returned format is without decimal digits
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string FormatNumberTwoDecimalDigitOrInt(decimal value)
    {
        return (value == (int)value) ? FormatAsIntWithCommaSeperator(Convert.ToInt32(value)) : FormatAsDecimalWithCommaSeperator(value);
    }

How can i use T in the function body?

如何在函数体中使用 T ?

What syntax should I use?

我应该使用什么语法?

采纳答案by Nikola Markovinovi?

You might use TypeCodefor switch:

您可以使用TypeCode进行切换:

switch (Type.GetTypeCode(typeof(T)))
{
    case TypeCode.Int32:
       break;
    case TypeCode.Decimal:
       break;
}

回答by SimpleVar

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

编辑:如果您只想精确处理 int 和 double,只需有两个重载:

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
{
}

回答by Adrian Thompson Phillips

Alternatively you could always do:

或者,您可以随时执行以下操作:

public static string FormatWithCommaSeparator<T>(T[] items)
{
    var itemArray = items.Select(i => i.ToString());

    return string.Join(", ", itemArray);
}

回答by Brian

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?
    }

回答by Paulie Waulie

You could instead of using generics use IConvertible

你可以代替使用泛型使用 IConvertible

    public static string FormatWithCommaSeperator(IConvertible value)
    {
            IConvertible convertable = value as IConvertible;
            if(value is int)
            {
                int iValue = convertable.ToInt32(null);
                //Return with format.
            }
            .....
    }
    public static string FormatWithCommaSeperator(IConvertible value)
    {
            IConvertible convertable = value as IConvertible;
            if(value is int)
            {
                int iValue = convertable.ToInt32(null);
                //Return with format.
            }
            .....
    }

回答by Tamir Daniely

In modern C#:

在现代 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}";
    }
}

回答by flam3

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:
        ...
}