What is the “base class” for C# numeric value types?

后端 未结 6 1639
太阳男子
太阳男子 2020-12-01 11:44

Say I want to have a method that takes any kind of number, is there a base class (or some other concept) that I can use?

As far as I know I have to make overloads f

6条回答
  •  清歌不尽
    2020-12-01 12:15

    What I do:

     public interface INumeric
     {
         T Zero { get; }
         T One { get; }
         T MaxValue { get; }
         T MinValue { get; }
         T Add(T a, T b);
         // T Substract(....
         // T Mult...
     }  
    
     public struct Numeric: 
         INumeric, 
         INumeric,
         INumeric,
         INumeric,
         // INumeric
     {
         int INumeric.Zero => 0;
         int INumeric.One => 1;
         int INumeric.MinValue => int.MinValue;
         int INumeric.MaxValue => int.MaxValue;
         int INumeric.Add(int x, int y) => x + y;
    
         // other implementations...
     }
    

    Now, you can use it in a method:

    bool IsZero(TNum ops, T number) 
       where TNum : INumeric
    {
       return number == ops.Zero;      
    }
    

    or extension method

     public static bool IsZero(this TNum ops, T number)
          where TNum : INumeric
     {
          return number == ops.Zero;
     }
    

    and in your code:

     ...
     var n = new Numeric(); // can be an static prop
    
     Console.WriteLine(IsZero(n, 5)); // false
     Console.WriteLine(IsZero(n, 0f)); // true
     Console.WriteLine(IsZero(n, "0")); // compiler error
    

    or, with extension method:

     Console.WriteLine(n.IsZero(5));  // false
     Console.WriteLine(n.IsZero(0f)); // true
     Console.WriteLine(n.IsZero("0")); // compiler error
    

提交回复
热议问题