Is there a constraint that restricts my generic method to numeric types?

后端 未结 21 2646
栀梦
栀梦 2020-11-21 05:48

Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

  • Int16
  • Int32
21条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:24

    Unfortunately .NET doesn't provide a way to do that natively.

    To address this issue I created the OSS library Genumerics which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.

    sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, and BigInteger

    The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.

    Here's an example of the code usage.

    public static T Sum(T[] items)
    {
        T sum = Number.Zero();
        foreach (T item in items)
        {
            sum = Number.Add(sum, item);
        }
        return sum;
    }
    
    public static T SumAlt(T[] items)
    {
        // implicit conversion to Number
        Number sum = Number.Zero();
        foreach (T item in items)
        {
            // operator support
            sum += item;
        }
        // implicit conversion to T
        return sum;
    }
    

提交回复
热议问题