📄 6.5.txt
字号:
Listing 6.5 Overflow Detection Using the Checked Keyword
using System;
namespace _6_CheckedUnchecked
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
// create 2 counters. One is checked, the other is not
Counter counter1 = new Counter( 1, false );
Counter counter2 = new Counter( 1, true );
// overflow detection disabled
for( int i = 1; i < 15; i++ )
{
// overflow will occur
counter1 *= i;
Console.WriteLine( counter1.Value );
}
try
{
// overflow detection enabled
for( int i = 1; i < 15; i++ )
{
// an exception is thrown when overflow occurs
counter2 *= i;
Console.WriteLine( counter2.Value );
}
}
catch( Exception e )
{
Console.WriteLine( “Exception caught: {0}”, e.Message );
}
}
}
class Counter
{
public int Value = 0;
public bool EnableCheck = false;
// passing true in second parameter will enable overflow detection
public Counter( int val, bool enableCheck )
{
this.Value = val;
this.EnableCheck = enableCheck;
}
public static Counter operator * ( Counter op1, int op2 )
{
int newVal;
if( op1.EnableCheck )
newVal = checked( op1.Value * op2 );
else
newVal = unchecked( op1.Value * op2 );
return new Counter( newVal, op1.EnableCheck );
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -