範例是參考MSDN做出來,很棒!!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace convert類別
- {
- class Program
- {
- static void Main(string[] args)
- {
- //object 型別的變數接受任何資料型別的值
- object[] ary = {true, -12, 163, 'x', new DateTime(2013,12,12),
- "105", "103.0", "-1", 1.00e2, 16.3e40};
- //迴圈
- foreach (object value in ary)
- {
- try
- {
- result = Convert.ToInt64(value);
- Console.WriteLine("{0} : {1} 轉換 {2} : {3}",
- value.GetType(), value, result.GetType(), result);
- Console.WriteLine();
- }
- catch (OverflowException) //產生溢位的狀況
- {
- Console.WriteLine("{0} : {1} : 溢位",
- value.GetType(), value);
- Console.WriteLine();
- }
- catch (FormatException) //格式不符合
- {
- Console.WriteLine("{0} : {1} : 格式不合",
- value.GetType(), value);
- Console.WriteLine();
- }
- catch (InvalidCastException) //無效的轉型
- {
- Console.WriteLine("{0} : {1} : 無效的轉型",
- value.GetType(), value);
- Console.WriteLine();
- }
- }
- }
- }
- }
沒有留言:
張貼留言