C# 是否可以检查两个变量的相加是否会导致溢出?

C# 是否可以检查两个变量的相加是否会导致溢出?,c#,.net,bit-manipulation,addition,C#,.net,Bit Manipulation,Addition,我的意思是,我能构建一个通用程序吗 public bool Overflows<T> ( T a, T b ) { // returns true or false based on whether // a + b overflows } 我想在bytes的情况下,我可以看看(a+b)

我的意思是,我能构建一个通用程序吗

public bool Overflows<T> ( T a, T b ) 
{
    // returns true or false based on whether
    // a + b overflows
} 

我想在
byte
s的情况下,我可以看看
(a+b)
(a+b)
。e、 g.我知道
255+1
溢出,因为
0
的结果小于
255
1
。或者,我可以将它们转换为更大的数据类型并进行如下检查

return ((int)a + (int)b) > (int)Byte.MaxValue;

但这并不适用于所有具有
+
运算符的数字类型。

最简单的方法是显式检查溢出并捕获相关异常(伪代码-请参见下文):

return ((int)a + (int)b) > (int)Byte.MaxValue;
public bool Overflows<T> ( T a, T b ) 
{
    {
        // the 'checked' keyword ensures an OverflowException is thrown 
        // as a result of a real integer overflow happening
        c = checked(a + b);  // * with 'T' this won't compile, see below
        return false;
    }
    catch (System.OverflowException e)
    {
        return true;
    }
}
if (typeof(T) == typeof(int))
    int i = checked((int)a + (int)b);
else if (typeof(T) == typeof(byte))
    byte b = checked((byte)a + (byte)b);
… etc.