6.5.txt

来自「《Microsoft Visual C# .NET 2003开发技巧大全》源代码」· 文本 代码 · 共 56 行

TXT
56
字号
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 + =
减小字号Ctrl + -
显示快捷键?