转换数据类型
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 在数据类型之间更改值的方法:
| 方法 | 转换为 | 示例 | Result |
|---|---|---|---|
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
目前,只需先确保该值可以转换,然后再尝试。 稍后,你将了解如何正常处理错误。