[C#]資料型別的轉換方法

[C#]資料型別的轉換方法

System.Convert方法
主要作用在於將基底資料型別轉換為其他的型別資料
Parse方法
轉換的內容 必須是字串
Cast方法
Cast方法是轉換能力 最強的,但需注意 轉換的內容 不得為字串
非字串轉換就用Cast方法,字串轉換 就用 Convert 或 Parse,因為常常會需要轉換型別
所以以上的規則一定要牢牢記住。
以下是個簡單的示範


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
{
    class Program
    {
        static void Main( string[] args)
        {
            string strDecimal="99.99" ;
            //錯誤       無法將型別 'string' 轉換為 'int' 
            //Console.WriteLine("Cast方法" + (int)strfloat);//轉換的內容 不得為字串
            Console .WriteLine("Convert方法" + Convert.ToDecimal(strDecimal));
            DateTime dt = DateTime .Parse( "2012/2/29"); //轉換的內容 必須是字串
            Console .WriteLine("Parse方法" + dt.ToString( "yyyy/MM/dd"));
            double i = 99.99;
            Console .WriteLine("Cast方法" + ( float)(i)); //轉換的內容 不得為字串 
            Console .ReadKey();
        }
    }
}

如有錯誤 歡迎指正