我正在尝试创建一个方法,可以将可空类型四舍五入到指定的小数位。理想情况下,我希望这是一个通用的方法,以便我可以像使用 Math.Round()
一样使用它来处理Double和Decimal。
我编写的代码无法编译,因为该方法无法(可以理解)解析,不知道该调用哪个重载。如何实现此功能?
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)'
}