C#数据类型转换详解(隐式转换和显式转换)
我们已经学习了 C# 中众多的数据类型:
这些数据可以互相转换,这就是所谓的数据类型的转换。
数据类型的转换概念是将一种数据类型转换成另一种数据类型,有隐式转换(implicit conversion)和显式转换(explicit conversion)等两种转换方式。
转换的特色是可以从比较小的容量数据类型,转移到比较大的容量数据类型,在转换过程数据不会遗失。
隐式转换如下表所示:
	
【实例 1】将 byte、short 和 char 转换成 int 整数。
下表所示为可以显式转换的数据类型表。
	
【实例 2】使用显式转换将 float 和 double 转换成 int。
	
	
- 整数类型数据,如 sbyte、byte、ulong 等;
 - 浮点数类型数据,如float、double 和 decimal;
 - 字符数据 char。
 
这些数据可以互相转换,这就是所谓的数据类型的转换。
数据类型的转换概念是将一种数据类型转换成另一种数据类型,有隐式转换(implicit conversion)和显式转换(explicit conversion)等两种转换方式。
C#隐式类型转换
所谓的隐式转换,是指不需要声明就可以进行转换,这种转换编译程序不需要进行检查。转换的特色是可以从比较小的容量数据类型,转移到比较大的容量数据类型,在转换过程数据不会遗失。
隐式转换如下表所示:
| 来源数据类型 | 目的数据类型 | 
|---|---|
| sbyte | short、int、long、float、double、decimal、decimal | 
| byte | short、ushort、int、uint、long、ulong、float、double、decimal | 
| short | int、long、float、double、decimal | 
| int | long、float、double、decimal | 
| char | ushort、int、uint、long、ulong、float、double、decimal | 
| float | double、decimal | 
| long | float、double、decimal | 
| ulong | float、double、decimal | 
【实例 1】将 byte、short 和 char 转换成 int 整数。
byte by = 123;
int x = by + 1;        // 隐式转换,byte转int
Console.WriteLine($"x = {x}");
short sh = 18;
x = sh;                // 隐式转换,short转int
Console.WriteLine($"x = {x}");
char ch = 'A';
x = ch;                // 隐式转换,char转int
Console.WriteLine($"x = {x}");
执行结果为:
	x = 124
	x = 18
	x = 65
C#显式类型转换
显式转换又称强制转换,这种转换需要转换运算符(casting operator),也就是在程序代码中使用下列语法转换:变量 = (新数据类型) 变量或表达式这类转换是强制转换,转换的特色是可以从比较大的容量数据类型,转移到比较小的容量数据类型,在转换过程有时会造成数据遗失。
下表所示为可以显式转换的数据类型表。
| 来源数据类型 | 目的数据类型 | 
|---|---|
| sbyte | byte、ushort、uint、ulong、char | 
| byte | sbyte、char | 
| short | sbyte、byte、ushort、uint、ulong、char | 
| ushort | sbyte、byte、short、char | 
| int | sbyte、byte、short、ushort、uint、ulong、char | 
| uint | sbyte、byte、short、ushort、int、char | 
| long | sbyte、byte、short、ushort、int、uint、long、char | 
| char | sbyte、byte、short | 
| float | sbyte、byte、short、ushort、int、uint、long、ulong、char、decimal | 
| double | sbyte、byte、short、ushort、int、uint、long、ulong、char、float、decimal | 
| decimal | sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double | 
【实例 2】使用显式转换将 float 和 double 转换成 int。
double d = 12345.6789;
int x = (int)d;        // double 转换成 int
Console.WriteLine($"x = {x}");
float f = 1234.567F;
x = (int)f;            // float 转换成 int
Console.WriteLine($"x = {x}");
执行结果为:
	x = 12345
	x = 1234
 ICP备案:
 公安联网备案: