如何创建一个可以返回double或decimal的通用C#方法?

Cri*_*onX 6 c# generics implicit

我有这样的方法:

private static double ComputePercentage(ushort level, ushort capacity)
{
      double percentage;
      if(capacity == 1)
        percentage = 1;

      // do calculations...
      return percentage;
}
Run Code Online (Sandbox Code Playgroud)

是否有可能使它成为像"类型T"这样的泛型类型,它可以返回十进制或双精度,具体取决于预期的方法类型(或放入函数的类型?)

我试过这样的东西,但是我无法让它工作,因为我不能将类似"1"的数字分配给泛型类型.我也尝试过使用"where T:" ushort capacity)但我还是想不出来.

private static T ComputePercentage<T>(ushort level, ushort capacity)
{
      T percentage;
      if(capacity == 1)
        percentage = 1; // error here

      // do calculations...
      return percentage;
}
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?我不确定,但我认为这篇文章可能暗示我正在尝试做的事情根本不可能.


编辑

感谢所有回复的人,许多好的答案.正如Tomas指出的那样,这可能最好用两种不同的方法完成.正如TreDubZedd和TcKs所指出的,获得我想要的功能的最好方法是使用隐式转换,它可以隐式返回double或decimal.

TcK*_*cKs 5

实际上,您不需要泛型,而是超载.但是,您需要通过IL支持的返回值类型进行重载,但C#不支持.

我为每个return的值类型优先选择两种方法:

static double  ComputePercentageDouble  (ushort level, ushort capacity)
static decimal ComputePercentageDecimal (ushort level, ushort capacity)
Run Code Online (Sandbox Code Playgroud)

替代方案可以是具有隐式转换运算符的custome类型:

decimal decimalPercentage = ComputePercentage( 1, 2 );
double  doublePercentage  = ComputePercentage( 1, 2 );

static DoubleDecimal ComputePercentage( ushort level, ushort capacity ) {
    DoubleDecimal percentage = default( DoubleDecimal );
    if ( capacity == 1 )
        percentage.Number = 1; // error here

    // do calculations...
    return percentage;
}


public struct DoubleDecimal {
    public decimal Number;

    public static implicit operator decimal( DoubleDecimal value ) {
        return value.Number;
    }
    public static implicit operator double( DoubleDecimal value ) {
        return (double)value.Number;
    }
}
Run Code Online (Sandbox Code Playgroud)