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

后端 未结 21 2596
栀梦
栀梦 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 06:36

    If all you want is use one numeric type, you could consider creating something similar to an alias in C++ with using.

    So instead of having the very generic

    T ComputeSomething(T value1, T value2) where T : INumeric { ... }
    

    you could have

    using MyNumType = System.Double;
    T ComputeSomething(MyNumType value1, MyNumType value2) { ... }
    

    That might allow you to easily go from double to int or others if needed, but you wouldn't be able to use ComputeSomething with double and int in the same program.

    But why not replace all double to int then? Because your method may want to use a double whether the input is double or int. The alias allows you to know exactly which variable uses the dynamic type.

提交回复
热议问题