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

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

    I created a little library functionality to solve these problems:

    Instead of:

    public T DifficultCalculation(T a, T b)
    {
        T result = a * b + a; // <== WILL NOT COMPILE!
        return result;
    }
    Console.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.
    

    You could write:

    public T DifficultCalculation(Number a, Number b)
    {
        Number result = a * b + a;
        return (T)result;
    }
    Console.WriteLine(DifficultCalculation(2, 3)); // Results in 8.
    

    You can find the source code here: https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number

提交回复
热议问题