现在的位置: 首页 > 综合 > 正文

C#.NET中的类型转换(关键字checked和unchecked)

2012年02月11日 ⁄ 综合 ⁄ 共 953字 ⁄ 字号 评论关闭
/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-17
 * Time: 11:10
 * 
 * 类型转换(关键字checked和unchecked)
 
*/
using System ;
using System .Windows .Forms ;
class Test
{
    
static void Main()
    {
//        int a=5;
//        long b;
//        b=a;//隐式转换
//        Console.WriteLine (b);
        
//        int aa;
//        long bb=5;
//        aa=(int)bb;//显式转换。由于as运算符必须与引用类型一起使用,而“int”是值类型,故这里不可写作aa=bb as int;
//        Console.WriteLine (aa);
        
//        int aaa;
//        long bbb=12345678901;
//        try
//        {
//            aaa=checked((int)bbb);//检测是否有异常
//        }
//        catch (System.OverflowException)
//        {
//            MessageBox.Show ("有溢出异常");
//            return;
//        }
//        Console.WriteLine (aaa);
        
        
int aaaa;
        
long bbbb=12345678901;
        
unchecked//checked和unchecked语句的两种写法
        {
            aaaa
=(int)bbbb;//unchecked 关键字用于取消整型算术运算和转换的溢出检查。
        }
        Console.WriteLine (aaaa);
//输出随机数据
    }
}

抱歉!评论已关闭.