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

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

    Topic is old but for future readers:

    This feature is tightly related to Discriminated Unions which is not implemented in C# so far. I found its issue here:

    https://github.com/dotnet/csharplang/issues/113

    This issue is still open and feature has been planned for C# 10

    So still we have to wait a bit more, but after releasing you can do it this way:

    static bool IntegerFunction(T value) where T : Int16 | Int32 | Int64 | ...
    

提交回复
热议问题