close

 

 

 

(1) 隱含轉換:

以下例子是使用於數字的轉換。如整數轉換為浮點數。以下是int隱含轉換為double的例子:

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            int a = 3;

            double b = a;

            Console.WriteLine(b);

 

            Console.Read();

        }

    }

}

執行後顯示:3

 

(2) 明確轉換:

明確轉換須在變數前用括號指出要轉換的變數型態,如:

(新變數型態)舊變數

明確轉換有可能在轉換後使變數的資訊變得不精確,相比之下隱含轉換就沒有這個問題。以下是double明確轉換為int的例子:

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            double b = 3.7;

            int a = (int)b;

            Console.WriteLine(a);

 

            Console.Read();

        }

    }

}

執行後顯示:3

b的值在經過無條件捨去運算後,被存入了a

 

 

(3) 其他常見的變數轉換:

變數.ToString():將變數轉換為字串顯示。

Convert.ToInt32(變數)變數轉換為int。如:

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string s = "311";

            int a = Convert.ToInt32(s);

            Console.WriteLine(a);

 

            Console.Read();

        }

    }

}

執行後顯示:311

 

 

 

 

上一篇:迴圈

下一篇:表單應用程式

按此前往C#完整教學目錄

arrow
arrow

    埃伯 發表在 痞客邦 留言(0) 人氣()