Polymorphic Numerics on .Net and In C#

后端 未结 3 897
耶瑟儿~
耶瑟儿~ 2021-01-14 13:05

It\'s a real shame that in .Net there is no polymorphism for numbers, i.e. no INumeric interface that unifies the different kinds of numerical types such as bool, byte, uint

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-14 13:26

    If you plan to use C# 4.0 then you can easily simulate generic mathematical operations using dynamic. Here is an example of a simple addition function (for more information see this blog):

    public static T Add(T a, T b) {
      dynamic ad = a;
      dynamic bd = b;
      return ad + bd;
    }
    

    I haven't played with this, so I can't say much about the performance. There will certainly be some performance price for using dynamic, but I think the DLR should be able to do very effective optimizations if you'll invoke the function multiple times. In fact, I won't be surprised if it had similar performance profile as Generic Operators mentioned above.

提交回复
热议问题