切换案例和泛型检查 [英] Switch case and generics checking
本文介绍了切换案例和泛型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将 int
和小数
格式的函数写入字符串中的方式不同
我有这样的代码:
我想将其重写为泛型:
public static string FormatAsIntWithCommaSeperator(int value)
{
if(value == 0 ||(value> -1&&< 1 ))
返回0;
return String.Format({0:#,###,###},value);
public static string FormatAsDecimalWithCommaSeperator(decimal value)
{
return String.Format({0:#,###,###。# #},value);
$ b public static string FormatWithCommaSeperator< T>(T value)其中T:struct
{
string formattedString = string.Empty; ((int)value == 0 ||(value> -1&& amp; amp;& amp; amp; amp;& amp; amp; amp; ;值<1))
返回0;
formattedString = String.Format({0:#,###,###},value);
}
//一些代码...
}
///< summary>
///如果数字是一个int - 返回的格式不带小数位
///< / summary>
///< param name =value>< / param>
///<返回>< /返回>
公共静态字符串FormatNumberTwoDecimalDigitOrInt(十进制值)
{
return(value ==(int)value)? FormatAsIntWithCommaSeperator(Convert.ToInt32(value)):FormatAsDecimalWithCommaSeperator(value);
}
如何在函数体中使用T?
我应该使用什么语法?
解决方案
您可以使用 TypeCode for switch:
<$ p $ (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Int32:
break;
case TypeCode.Decimal:
break;
}
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 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?
What syntax should I use?
解决方案
You might use TypeCode for switch:
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Int32:
break;
case TypeCode.Decimal:
break;
}
这篇关于切换案例和泛型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文