gpt4 book ai didi

c# - 开关盒和泛型检查

转载 作者:可可西里 更新时间:2023-11-01 03:12:07 25 4
gpt4 key购买 nike

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

我有这个代码:

我想将它重写为泛型:

    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);
}

如何在函数体中使用 T?

我应该使用什么语法?

最佳答案

您可以使用 TypeCode enum对于开关:

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

从 C# 7.0 开始,您可以使用 pattern matching :

switch (obj)
{
case int i:
...
break;
case decimal d:
...
break;
case UserDefinedType u:
...
break;
}

从 C# 8.0 开始,您可以使用 switch expressions :

string result = obj switch {
int i => $"Integer {i}",
decimal d => $"Decimal {d}",
UserDefinedType u => "User defined {u}",
_ => "unexpected type"
};

关于c# - 开关盒和泛型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9802325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com