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

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

    There is no way to restrict templates to types, but you can define different actions based on the type. As part of a generic numeric package, I needed a generic class to add two values.

        class Something
        {
            internal static TCell Sum(TCell first, TCell second)
            {
                if (typeof(TCell) == typeof(int))
                    return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));
    
                if (typeof(TCell) == typeof(double))
                    return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));
    
                return second;
            }
        }
    

    Note that the typeofs are evaluated at compile time, so the if statements would be removed by the compiler. The compiler also removes spurious casts. So Something would resolve in the compiler to

            internal static int Sum(int first, int second)
            {
                return first + second;
            }
    

提交回复
热议问题