轉載至:http://www.wretch.cc/blog/willybun/9173323

 

有三種轉換方法:
1. System.Convert
2. 型別.Parse()
3. 指定轉換 Cast

由於Visual C# 2005是屬於strongly-type而非weakly-type,所以在run time時期
就必須明確地宣告才能通過compiler的嚴格考驗。

1. System.Convert轉換方法:
ToBoolean(), ToByte(), ToChar(), ToDateTime(), ToDecimal(), ToDouble(),
ToInt32(), ToSByte(), ToSingle(), ToString()

Ex:
string telephone;
int myTelephone;

teltephone = "0266668888";

myTelephone = System.Convert.ToInt32(telephone);


2. Parse方法
主要處理的對象是string
Boolean.Parse(), Byte.Parse(), Char.Parse(), DateTime.Parse(),
Decimal.Parse(), Double.Parse(), Int32.Parse(), SByte.Parse(),
Single.Parse(), TimeSpan.Parse()
常犯的錯誤就是轉的內容不是字串!!!

Ex:
DateTime DT;
string date = "2008/6/1"

DT = DateTime.Parse(date); // data是字串,正確!!


3. Cast轉換
語法: 變數名稱1 = (變數1的type) 變數名稱2;

Ex:
double FM = 99.9;
int Radio;

Radio = (int) FM;

arrow
arrow
    全站熱搜

    東勢厝滴yang 發表在 痞客邦 留言(0) 人氣()