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

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

    There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.

    I'd go further and say we need

    static bool GenericFunction(T value) 
        where T : operators( +, -, /, * )
    

    Or even

    static bool GenericFunction(T value) 
        where T : Add, Subtract
    

    Unfortunately you only have interfaces, base classes and the keywords struct (must be value-type), class (must be reference type) and new() (must have default constructor)

    You could wrap the number in something else (similar to INullable) like here on codeproject.


    You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.

提交回复
热议问题