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

后端 未结 21 2600
栀梦
栀梦 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:16

    Probably the closest you can do is

    static bool IntegerFunction(T value) where T: struct
    

    Not sure if you could do the following

    static bool IntegerFunction(T value) where T: struct, IComparable
    , IFormattable, IConvertible, IComparable, IEquatable
    

    For something so specific, why not just have overloads for each type, the list is so short and it would possibly have less memory footprint.

提交回复
热议问题