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

后端 未结 21 2683
栀梦
栀梦 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条回答
  •  旧时难觅i
    2020-11-21 06:17

    Unfortunately you are only able to specify struct in the where clause in this instance. It does seem strange you can't specify Int16, Int32, etc. specifically but I'm sure there's some deep implementation reason underlying the decision to not permit value types in a where clause.

    I guess the only solution is to do a runtime check which unfortunately prevents the problem being picked up at compile time. That'd go something like:-

    static bool IntegerFunction(T value) where T : struct {
      if (typeof(T) != typeof(Int16)  &&
          typeof(T) != typeof(Int32)  &&
          typeof(T) != typeof(Int64)  &&
          typeof(T) != typeof(UInt16) &&
          typeof(T) != typeof(UInt32) &&
          typeof(T) != typeof(UInt64)) {
        throw new ArgumentException(
          string.Format("Type '{0}' is not valid.", typeof(T).ToString()));
      }
    
      // Rest of code...
    }
    

    Which is a little bit ugly I know, but at least provides the required constraints.

    I'd also look into possible performance implications for this implementation, perhaps there's a faster way out there.

提交回复
热议问题