轉換資料類型

已完成

Tip

有關更多詳細信息,請參閱 文本和圖像 選項卡!

由於 C# 是強型別的,有時你需要明確將一個值從一種資料型態轉換到另一種。 這在處理使用者輸入時尤其重要,因為 Console.ReadLine() 即使使用者輸入數字,也會回傳文字(a string)。

為什麼皈依很重要

請考慮以下常見案例:

Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int nextYear = ageInput + 1;    // ERROR! Can't add int to string

要用使用者輸入做數學運算,你必須先把字串轉換成數字。

轉換方法

C# 提供了 Convert 在資料型別間變更值的方法:

方法 轉換為 範例 結果
Convert.ToInt32() int Convert.ToInt32("42") 42
Convert.ToDecimal() 十進位 Convert.ToDecimal("19.99") 19.99m
Convert.ToDouble() double Convert.ToDouble("3.14") 3.14
Convert.ToString() 字串 Convert.ToString(42) "42"

以下是修正先前情況的方法:

Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = Convert.ToInt32(ageInput);
int nextYear = age + 1;
Console.WriteLine($"Next year you'll be {nextYear}");

你可以自己用 C# 程式碼編輯器執行這段程式碼。

解析方法

另一種將字串轉換為數字的方法如下 Parse :

int age = int.Parse("25");
decimal price = decimal.Parse("19.99");
double average = double.Parse("87.5");

兩者都做Convert.ToInt32()int.Parse()類似的事——用你喜歡的風格。

數值類型之間的轉型

若要在數值型別之間轉換 (例如從decimal轉為int),請使用轉型 ,將目標類型置於括弧中:

decimal price = 19.99m;
int wholePrice = (int)price;         // Casts to int: 19 (decimal dropped)
Console.WriteLine(wholePrice);       // Output: 19

你也可以施放以保持除法時的十進位精確:

int first = 7;
int second = 2;
decimal result = (decimal)first / (decimal)second;
Console.WriteLine(result);           // Output: 3.5

無效轉換會發生什麼事?

如果你嘗試轉換一個無法被解讀為數字的值,C# 會拋出錯誤:

int number = Convert.ToInt32("hello");    // ERROR: Input string was not in a correct format

目前先確定數值能轉換再嘗試。 之後,你會學會如何優雅地處理錯誤。