将泛型参数传递给非泛型方法

时间:2012-05-21 09:46:46

标签: c# .net generics overloading

我正在尝试创建一个方法,将nullicbles舍入到给定的小数位。理想情况下,我希望这是一个通用的,以便我可以使用双倍和小数作为Math.Round()许可。

我下面编写的代码将无法编译,因为无法(理解)解析该方法,因为无法知道调用哪个重载。如何实现这一目标?

internal static T? RoundNullable<T>(T? nullable, int decimals) where T : struct
{
    Type paramType = typeof (T);

    if (paramType != typeof(decimal?) && paramType != typeof(double?))
        throw new ArgumentException(string.Format("Type '{0}' is not valid", typeof(T)));

    return nullable.HasValue ? Math.Round(nullable.Value, decimals) : (T?)null; //Cannot resolve method 'Round(T, int)'
 }

2 个答案:

答案 0 :(得分:7)

  

如何实现这一目标?

就个人而言,我会摆脱你的通用方法。它无论如何只对两个类型的参数有效 - 将它分成带有两个重载的重载方法:

internal static double? RoundNullable(double? nullable, int decimals)
{
    return nullable.HasValue ? Math.Round(nullable.Value, decimals)
                             : (double?) null;
}

internal static decimal? RoundNullable(decimal? nullable, int decimals)
{
    return nullable.HasValue ? Math.Round(nullable.Value, decimals)
                             : (decimal?) null;
}

如果您必须使用通用版本,请根据Dave的回答有条件地调用它,直接使用反射调用它,或者如果您需要使用dynamic使用C#4和.NET 4。

答案 1 :(得分:2)

鉴于您已经在进行类型检查,只需在代码流中使用它:

if (paramType == typeof(decimal?))
...
    Math.Round((decimal)nullable.Value, decimals)
else if(paramType == typeof(double?))
    Math.Round((double)nullable.Value, decimals)
相关问题