在C#中,OverflowException不会引发(在VB中,默认情况下会引发异常)。
为了获得排他性,您必须将代码嵌入checked上下文中:
byte value = 241;
checked
{
try
{
sbyte newValue = (sbyte) value;
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
value.GetType().Name, value,
newValue.GetType().Name, newValue);
}
catch (OverflowException)
{
Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue);
}
}
MSDN更详细地解释:
为了使算术,转换或转换操作抛出OverflowException,该操作必须在检查的上下文中发生。默认情况下,将检查Visual Basic中的算术运算和溢出。在C#中,它们不是。如果操作发生在未经检查的上下文中,则结果将被舍弃,方法是丢弃所有不适合目标类型的高阶位。