zoukankan      html  css  js  c++  java
  • 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}
    b = {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:NickcodeC#	estCheckOve
    rflowCheckOverflowProgram.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})
  • 相关阅读:
    对后端返回的图片添加点击事件
    Unity3D 优化NGUI纹理
    Unity 给Mono脚本添加Try Catch工具
    Unity3D Shader 高斯模糊
    Unity3D Shader 空气扭动效果
    Unity3D Shader 马赛克后期效果
    Unity3D Shader 半兰伯特光照模型
    Unity3D Shader水波效果
    Unity3D Shader 模型流光效果
    Unity3D Shader 按百分比裁剪模型
  • 原文地址:https://www.cnblogs.com/numbqq/p/5345076.html
Copyright © 2011-2022 走看看