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


posted on 2008-12-30 14:37  万一  阅读(2170)  评论(0编辑  收藏  举报