切换案例和generics检查

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

我有这个代码:

我想把它重写为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 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... } ///  /// If the number is an int - returned format is without decimal digits ///  ///  ///  public static string FormatNumberTwoDecimalDigitOrInt(decimal value) { return (value == (int)value) ? FormatAsIntWithCommaSeperator(Convert.ToInt32(value)) : FormatAsDecimalWithCommaSeperator(value); } 

我如何在函数体中使用T?

我应该使用什么语法?

您可以使用TypeCode进行切换:

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

编辑:如果你只想处理int和double,只需要两个重载:

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

如果你坚持使用generics:

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

要么

 if (value is int) { int iValue = (int)(object)value; } else if (value is double) { double dValue = (double)(object)value; } else { } 

在现代C#中:

 public static string FormatWithCommaSeperator(T value) where T : struct { switch (value) { case int i: return $"integer {i}"; case double d: return $"double {d}"; } } 

你可以代替使用generics使用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 FormatWithCommaSeparator(T[] items) { var itemArray = items.Select(i => i.ToString()); return string.Join(", ", itemArray); } 

你可以检查变量的类型;

  public static string FormatWithCommaSeperator(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? }