C# 类型转换
最后修改于 2025 年 6 月 3 日
本文介绍了如何使用 Convert 类在 C# 中转换类型。
Convert 类提供了将基本数据类型转换为另一种数据类型的方法,从而确保在应用程序中实现无缝类型转换。
Convert 类位于 System 命名空间中,简化了常见的类型转换任务,例如在数值、字符串和布尔类型之间进行转换。
类型转换(或 类型转换)是指将值从一种数据类型更改为另一种数据类型。 在 C# 中,有两种类型的转换:
- 隐式转换: 也称为强制转换,当编译器安全地将一种类型转换为另一种类型而不会丢失数据时,会自动发生。
- 显式转换: 需要手动干预,通常使用强制转换或转换方法,并且可能导致数据截断或异常。
C# 转换类型
在下一个示例中,我们将介绍三种数据转换方法。
int n = 12; string s = "15"; string res = n + s; Console.WriteLine(res); int res2 = int.Parse(s) + n; Console.WriteLine(res2); int res3 = Convert.ToInt32(s) + n; Console.WriteLine(res3);
该程序定义一个整数和一个字符串。 我们将这两个值相加。
int res = n + s;
默认情况下,编译器隐式地将整数转换为字符串,并将两个字符串相加。
int res2 = int.Parse(s) + n;
我们可以使用 int.Parse 方法显式地将字符串转换为整数,并将两个整数相加。
int res3 = Convert.ToInt32(s) + n;
或者,我们可以使用 Convert.ToInt32 方法。 Convert 类包含多种用于常见类型转换的方法。
$ dotnet run 1215 27 27
C# Conver.ToBoolean
Conver.ToBoolean 方法将指定值转换为等效的布尔值。
double n1 = 0.3; int n2 = 3; int n3 = 0; int n4 = -1; decimal d = 0.35m; Console.WriteLine(Convert.ToBoolean(n1)); Console.WriteLine(Convert.ToBoolean(n2)); Console.WriteLine(Convert.ToBoolean(n3)); Console.WriteLine(Convert.ToBoolean(n4)); Console.WriteLine(Convert.ToBoolean(d));
在该程序中,我们将 double、int 和 decimal 值转换为布尔值。
$ dotnet run True True False True True
C# 转换十六进制字符串
Convert.ToHexString 将 8 位无符号整数数组转换为其等效的字符串表示形式,该字符串表示形式使用大写十六进制字符进行编码。
Convert.FromHexString 将指定的字符串(该字符串将二进制数据编码为十六进制字符)转换为等效的 8 位无符号整数数组。
using System.Text; string msg = "an old falcon"; byte[] data = Encoding.ASCII.GetBytes(msg) ; string hexstr = Convert.ToHexString(data); Console.WriteLine(hexstr); byte[] data2 = Convert.FromHexString(hexstr); Console.WriteLine(Encoding.ASCII.GetString(data2));
该程序将消息转换为十六进制字符串,反之亦然。
$ dotnet run 616E206F6C642066616C636F6E an old falcon
C# Convert.ToBase64String
Convert.ToBase64String 将 8 位无符号整数数组转换为其等效的字符串表示形式,该字符串表示形式使用 base-64 数字进行编码。
相反,Convert.FromBase64String 方法将指定的字符串(该字符串将二进制数据编码为 base-64 数字)转换为等效的 8 位无符号整数数组。
Base64 编码广泛用于发送电子邮件附件。
using System.Text;
string msg = "an old falcon";
byte[] data = Encoding.ASCII.GetBytes(msg);
Console.WriteLine(BitConverter.ToString(data));
string base64 = Convert.ToBase64String(data);
Console.WriteLine(base64);
Console.WriteLine("---------------------");
byte[] data2 = Convert.FromBase64String(base64);
Console.WriteLine(BitConverter.ToString(data));
Console.WriteLine(Encoding.ASCII.GetString(data));
在该程序中,我们将字符串转换为字节数组,然后将数组转换为 Base64 字符串。 然后我们逆转该过程。
$ dotnet run 61-6E-20-6F-6C-64-20-66-61-6C-63-6F-6E YW4gb2xkIGZhbGNvbg== --------------------- 61-6E-20-6F-6C-64-20-66-61-6C-63-6F-6E an old falcon
C# Convert.ToDateTime
Convert.ToDateTime 将日期和时间的指定字符串表示形式转换为等效的日期和时间值。
public static DateTime ToDateTime (string? value);
这是该方法的语法。
DateTime now = DateTime.Now; Console.WriteLine(now); string d = now.ToString(); Console.WriteLine(d); DateTime dt = Convert.ToDateTime(d); Console.WriteLine(dt);
在该示例中,我们将当前日期时间转换为字符串,然后将该字符串转换回日期时间。
$ dotnet run 6/3/2025 1:26:21 PM 6/3/2025 1:26:21 PM 6/3/2025 1:26:21 PM
C# Convert.ToDecimal
Convert.ToDecimal 方法将指定的值转换为 decimal 类型,该类型适用于高精度计算,例如金融应用程序。
string price = "123.456";
int quantity = 5;
double rate = 0.075;
decimal priceDecimal = Convert.ToDecimal(price);
decimal quantityDecimal = Convert.ToDecimal(quantity);
decimal rateDecimal = Convert.ToDecimal(rate);
decimal total = priceDecimal * quantityDecimal * (1 + rateDecimal);
Console.WriteLine($"Price: {priceDecimal:C}");
Console.WriteLine($"Quantity: {quantityDecimal}");
Console.WriteLine($"Tax Rate: {rateDecimal:P}");
Console.WriteLine($"Total with Tax: {total:C}");
在此示例中,我们使用 Convert.ToDecimal 将字符串、整数和双精度浮点数转换为 decimal。 这些值用于计算含税总价,展示了 decimal 在财务计算中的精度。 输出格式化结果以提高可读性。
$ dotnet run Price: $123.46 Quantity: 5 Tax Rate: 7.50% Total with Tax: $664.26
C# Convert with Nullable Types
Convert 类可以处理可空类型,允许在值可能为空时进行安全转换。 对于数字转换,Convert.ToInt32 等方法将 null 视为零,这对于处理可选数据非常有用。
string? nullableString = null;
string validString = "42";
object? nullableObject = null;
int result1 = Convert.ToInt32(nullableString); // Converts null to 0
int result2 = Convert.ToInt32(validString);
int result3 = Convert.ToInt32(nullableObject); // Converts null to 0
Console.WriteLine($"Nullable string to int: {result1}");
Console.WriteLine($"Valid string to int: {result2}");
Console.WriteLine($"Nullable object to int: {result3}");
此程序演示了 Convert.ToInt32 如何处理可为空的字符串和对象。 空值转换为 0,而有效字符串转换为其整数等效值。 这在处理可能缺失或可选的数据时特别有用。
$ dotnet run Nullable string to int: 0 Valid string to int: 42 Nullable object to int: 0
C# Convert with Overflow Checking
Convert 类可以在 checked 上下文中使用,以检测数值类型之间转换时的溢出,从而确保关键计算中的安全类型转换。
double largeNumber = 1_000_000_000_000;
string largeString = "2147483648"; // Beyond int.MaxValue
try
{
checked
{
// Throws OverflowException
int intFromDouble = Convert.ToInt32(largeNumber);
Console.WriteLine(intFromDouble);
}
}
catch (OverflowException e)
{
Console.WriteLine($"Overflow converting double: {e.Message}");
}
try
{
checked
{
// Throws OverflowException
int intFromString = Convert.ToInt32(largeString);
Console.WriteLine(intFromString);
}
}
catch (OverflowException e)
{
Console.WriteLine($"Overflow converting string: {e.Message}");
}
此示例在 checked 块中使用 Convert.ToInt32 将一个大的双精度浮点数和一个字符串转换为整数。 这两个转换都超过了 int.MaxValue,从而触发了 OverflowException。 这演示了如何在关注溢出的情况下安全地使用 Convert。
$ dotnet run Overflow converting double: Value was either too large or too small for an Int32. Overflow converting string: Value was either too large or too small for an Int32.
来源
在本文中,我们展示了如何使用 Convert 在 C# 中转换类型。
作者
列出所有 C# 教程。