C# 类型转换
最后修改于 2023 年 7 月 5 日
在本文中,我们将展示如何使用 Convert
类在 C# 中转换类型。
Convert
将基本数据类型转换为另一种基本数据类型。
Convert 类位于 System 命名空间中。
类型转换是指将一个数据类型的实体更改为另一种数据类型。 有两种类型的转换:隐式转换和显式转换。 隐式类型转换(也称为强制转换)是编译器自动进行的类型转换。
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 10/23/2022 6:58:09 PM 10/23/2022 6:58:09 PM 10/23/2022 6:58:09 PM
C# Convert.ToDecimal
Convert.ToDecimal
方法将指定的值转换为 decimal
类型,该类型适用于高精度计算,例如财务应用程序。
using System; class Program { static void Main() { 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
将字符串、整数和 double 转换为 decimal
。 这些值用于计算含税总价,展示了 decimal
在财务计算中的精度。 输出格式化结果以提高可读性。
$ dotnet run Price: $123.46 Quantity: 5 Tax Rate: 7.50% Total with Tax: $664.26
C# 使用可空类型进行转换
Convert
类可以处理可空类型,允许在值可能为空时进行安全转换。 像 Convert.ToInt32
这样的方法将 null 视为数字转换的零,这对于处理可选数据非常有用。
using System; class Program { static void Main() { 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
类可以在 checked
上下文中使用,以检测在数值类型之间转换时的溢出,从而确保在关键计算中进行安全的类型转换。
using System; class Program { static void Main() { double largeNumber = 1_000_000_000_000; string largeString = "2147483648"; // Beyond int.MaxValue try { checked { int intFromDouble = Convert.ToInt32(largeNumber); // Throws OverflowException Console.WriteLine(intFromDouble); } } catch (OverflowException e) { Console.WriteLine($"Overflow converting double: {e.Message}"); } try { checked { int intFromString = Convert.ToInt32(largeString); // Throws OverflowException Console.WriteLine(intFromString); } } catch (OverflowException e) { Console.WriteLine($"Overflow converting string: {e.Message}"); } } }
本示例在 checked
块中使用 Convert.ToInt32
将一个大的 double 和一个字符串转换为整数。 这两个转换都超过了 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# 教程。