Problem Source: in c # programming, some numeric primitive types such as Int16, Int32, Int64, and Decimal are often involved in addition, subtraction, multiplication, division, and so on. For example, we often write the following method, which is used to calculate the sum of the numbers from 0 to the 32-bit integer input (no special circumstances such as overflow are considered ):
1
internal
static
Int32 Sum(
int
num)
2
{
3
Int32 sum = 0;
4
for
(Int32 i = 0; i < num; i++)
5
{
6
sum += i;
7
}
8
return
sum;
9
}
Similarly, if we need to return the type and input type to other primitive types, such as Decimal and Int64, normally we will modify the return and input parameter types in the above Code, for example, you can sum Int64 as follows:
1
internal
static
Int64 Sum(Int64 num)
2
{
3
Int64 sum = 0;
4
for
(Int64 i = 0; i < num; i++)
5
{
6
sum += i;
7
}
8
return
sum;
9
}
But how many different primitive numeric types do you need to write such a method (here we do not consider the mutual conversion between some numeric primitive types), resulting in method expansion and code bloated? After analyzing the code above, we found that the number of parameters and the calculation format are very similar. Without a doubt, we will think of abstracting a common generic method to solve the Calculation Problem of the numeric primitive type.
In <CLR Via C #>, jeffrey Richter gives an example and tries his best to implement the following generic method to implement a generic type variable as the operand:
01
internal
static
class
UsingGenericTypeVariablesAsOperands
02
{
03
private
static
T Sum<T>(T num) where T :
struct
04
{
05
T sum =
default
(T);
06
for
(T n =
default
(T); n < num; n++)
07
sum += n;
08