C#文法練習(4):タイプ変換

2688 ワード

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