m.e*_*son 3 .net c# 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)'
}
Run Code Online (Sandbox Code Playgroud)
这将如何实现?
就个人而言,我只是摆脱你的通用方法.它无论如何只对两个类型的参数有效 - 将它分成带有两个重载的重载方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
如果必须使用通用版本,请根据Dave的回答有条件地调用它,直接使用反射调用它,或者dynamic如果您使用的是C#4和.NET 4则使用它.
| 归档时间: |
|
| 查看次数: |
1258 次 |
| 最近记录: |