gpt4 book ai didi

c# - 将泛型参数传递给非泛型方法

转载 作者:行者123 更新时间:2023-11-30 13:48:55 25 4
gpt4 key购买 nike

我正在尝试创建一种方法,将可空值四舍五入到给定的小数位。理想情况下,我希望这是一个泛型,这样我就可以在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com