C#基本语法学习(十)

C#数据进行显示转换时有可能会出现溢出的情况这时可以用关键字checked进行检查是否溢出:

  checked(<expression>)    检查溢出
  unchecked(<expression>)    不检查溢出

如果使用checked检查溢出,一旦溢出就会抛出System.OverflowException,同时也可以通过配置IDE来默认使能溢出检查,除非加上unchecked,否则一旦溢出就会抛出异常,配置工程默认打开溢出检查如下:

使用checked例子如下:

 1         static void Main(string[] args)
 2         {
 3             Int32 a = 123456;
 4             Int16 b = 0;
 5 
 6             b = checked((Int16)a);
 7 
 8             Console.WriteLine("a = {0}\r\nb = {1}", a, b);
 9 
10             Console.WriteLine("Press any key to exit!");
11             Console.ReadKey();
12         }

运行结果:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in
an overflow.
   at CheckOverflow.Program.Main(String[] args) in d:\Nick\code\C#\test\CheckOve
rflow\CheckOverflow\Program.cs:line 16

    转换溢出抛出异常。

 

C#中使用params关键字定义可变参数方法,但必须是最后一个参数。

  static <returnType> <FunctionName>(<p1Type> <p1Name>, ...,params <type>[] <name>);

 1         //定义可变参数方法
 2         static int GetSum(params int[] array)
 3         {
 4             int sum = 0;
 5 
 6             foreach (int a in array)
 7             {
 8                 sum += a;    
 9             }
10 
11             return sum;
12         }
13 
14         //调用
15         GetSum(new int[] { 1, 2, 3, 4, 5, 6, 7, 8});
16         GetSum(new int[] { 1, 2, 3, 4, 5})

 

转载于:https://www.cnblogs.com/numbqq/p/5345076.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值