作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一种方法,将可空值四舍五入到给定的小数位。理想情况下,我希望这是一个泛型,这样我就可以在 Math.Round()
允许的情况下将它与 double 和小数一起使用。
我在下面编写的代码将无法编译,因为该方法无法(可以理解)解析,因为无法知道要调用哪个重载。这将如何实现?
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)'
}
最佳答案
How would this be achieved?
就我个人而言,我只想摆脱您的通用方法。它只对两种类型的参数有效 - 将其拆分为具有两个重载的重载方法:
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 的回答有条件地调用它,直接通过反射调用它,或者如果您使用的是 C# 4,则使用 dynamic
和 .NET 4。
关于c# - 将泛型参数传递给非泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682956/
我是一名优秀的程序员,十分优秀!