VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • c#语法练习4 类型转换

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
 

  使用 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();
  }
}


		

 



相关教程