zoukankan      html  css  js  c++  java
  • C# 语法练习(4): 类型转换


    使用 Convert 类:
    ToBoolean  -> bool
    ToByte     -> byte
    ToChar     -> char
    ToDateTime -> DateTime
    ToDecimal  -> decimal
    ToDouble   -> double
    ToInt16    -> short
    ToInt32    -> int
    ToInt64    -> long
    ToSByte    -> sbyte
    ToSingle   -> float
    ToString   -> string
    ToUInt16   -> ushort
    ToUInt32   -> uint
    ToUInt64   -> ulong
    


    using System;
    
    class MyClass
    {
        static void Main()
        {
            int num;
            string str;
    
            num = 99;
            str = Convert.ToString(num);
            Console.WriteLine(str);
    
            str = "123";
            num = Convert.ToInt32(str);
            Console.WriteLine(num);
    
            Console.ReadKey();
        }
    }
    

    隐式转换, 只要容得下就行:

    using System;
    
    class MyClass
    {
        static void Main()
        {
            byte n = byte.MaxValue;
    
            short n1 = n;
            int   n2 = n;
            long  n3 = n;
    
            Console.WriteLine("{0},{1},{2}", n1, n2, n3); //255,255,255
    
            Console.ReadKey();
        }
    }
    

    显示转换, 可能会因溢出而丢失数据:

    using System;
    
    class MyClass
    {
        static void Main()
        {
            ulong n = ulong.MaxValue;
    
            byte   n1 = (byte)n;
            ushort n2 = (ushort)n;
            uint   n3 = (uint)n;
    
            Console.WriteLine("{0},{1},{2}", n1, n2, n3); //255,65535,4294967295
    
            Console.ReadKey();
        }
    }
    

    溢出检查:

    using System;
    
    class MyClass
    {
        static void Main()
        {
            int i;
            byte b;
    
            i = 255;
            b = (byte)i;             /* i 在 byte 的范围内, 不会溢出 */
            b = unchecked((byte)i);  /* 同上一行, 不做溢出检查 */
            Console.WriteLine(b);    // 255
    
            i++;
            b = (byte)i;             /* i 超出 byte 的范围内, 会溢出 */
            b = unchecked((byte)i);  /* 同上一行, 不做溢出检查 */
            Console.WriteLine(b);    // 0
    
            i = 255;
            b = checked((byte)i);    /* 可以通过溢出检测 */
            Console.WriteLine(b);    // 255
    
            i++;
            b = checked((byte)i);    /* 不能通过溢出检测, 会报错 */
            Console.WriteLine(b);
    
            Console.ReadKey();
        }
    }
    

  • 相关阅读:
    pfofinet和S7
    A1010 Radix [二分/******]
    A1005 Spell It Right
    最大回文子串长度 [dp]
    HDU 1159 Common Subsequence [最长公共子序列]
    1045 Favorite Color Stripe [动态规划/最长不下降子序列]
    1007 Maximum Subsequence Sum [动态规划]
    数塔问题(递归/递推)
    hdu 畅通工程 [Kruskal/Prime]
    1087 All Roads Lead to Rome [dj]
  • 原文地址:https://www.cnblogs.com/del/p/1365267.html
Copyright © 2011-2022 走看看