简体   繁体   English

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

[英]Pass generic parameter to a non-generic method

I'm attempting to create a method which will round nullables to a given decimal place. 我正在尝试创建一个方法,将nullicbles舍入到给定的小数位。 Ideally I'd like this to be a generic so that I can use it with both Doubles and Decimals as Math.Round() permits. 理想情况下,我希望这是一个通用的,以便我可以将它与双打和小数一起使用,因为Math.Round()允许。

The code I have written below will not compile because the method cannot be (understandably) resolved as it's not possible to know which overload to call. 我在下面编写的代码将无法编译,因为无法(可理解)解析该方法,因为无法知道调用哪个重载。 How would this be achieved? 这将如何实现?

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? 这将如何实现?

Personally, I would just get rid of your generic method. 就个人而言,我只是摆脱你的通用方法。 It's only valid for two type arguments anyway - split it into an overloaded method with two overloads: 它无论如何只对两个类型的参数有效 - 将它分成带有两个重载的重载方法:

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;
}

If you must use the generic version, either invoke it conditionally as per Dave's answer, invoke it with reflection directly, or use dynamic if you're using C# 4 and .NET 4. 如果必须使用通用版本,请根据Dave的回答有条件地调用它,直接使用反射调用它,或者如果使用C#4和.NET 4则使用dynamic版本。

Given you're already doing a type-check, simply use that in your code flow: 鉴于您已经在进行类型检查,只需在代码流中使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM