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

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

    What is the point of the exercise?

    As people pointed out already, you could have a non-generic function taking the largest item, and compiler will automatically convert up smaller ints for you.

    static bool IntegerFunction(Int64 value) { }
    

    If your function is on performance-critical path (very unlikely, IMO), you could provide overloads for all needed functions.

    static bool IntegerFunction(Int64 value) { }
    ...
    static bool IntegerFunction(Int16 value) { }
    

提交回复
热议问题