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

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

    This question is a bit of a FAQ one, so I'm posting this as wiki (since I've posted similar before, but this is an older one); anyway...

    What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).

    This has methods like T Add(T x, T y), and other variants for arithmetic on different types (like DateTime + TimeSpan).

    Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.

    Some additional background on why this is tricky is here.

    You may also want to know that dynamic (4.0) sort-of solves this issue indirectly too - i.e.

    dynamic x = ..., y = ...
    dynamic result = x + y; // does what you expect
    

提交回复
热议问题