Windows Phone 7手机开发Net培训期待与您交流!
实际编程中,经常遇到类型的相互转换问题,如一个int类型要转换成一个long类型。类型转换方法分为隐式类型转换和显式类型转换,也可以采用Convert类的方法实现类型转换。
1
.隐式数值转换
数值转换是指在整数类型、实数类型和字符类型之间的转换。
sbyte
类型向
int
类
型转换是一种隐式数值类型转换,转换一般不会失败,也不会丢失数据。例如:
sbyte a = 100;
int b = a;
原
始
类
型
|
可转换到的类型
|
可能有信息丢失
|
sbyte
|
short, int, long, float, double, decimal
|
|
byte
|
short, ushort, int, uint, long, ulong, float,
double, decimal
|
|
short
|
int, long, float, double, decimal
|
|
ushort
|
int, uint, long, ulong, float, double, decimal
|
|
int
|
long, float, double, decimal
|
float
|
uint
|
long, ulong, float, double, decimal
|
float
|
long
|
float, double, decimal
|
float
,
double
|
ulong
|
float, double, decimal
|
float
,
double
|
char
|
ushort, int, uint, long, ulong, float, double,
decimal
|
|
float
|
double
|
|
2.显式类型转换
显式类型转换只有在某些情况下实现转换,规则复杂,需要用户正确指定要转
换的类型,又称强制类型转换。
1
.显式数值转换
int
类型向
byte
类型转换就是一种显式数值类型转换。例如:
int b = 100;
sbyte a =(byte)b;
sbyte
取值范围是
0
~
255
,当
int b
显式转换为
sbyte
时不会丢失信息。
int b = 1000;
sbyte a =(byte)b;
则会丢失信息,这是显式数值转换过程要注意的。
原
始
类
型
|
可转换到的类型
|
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, ulong, char
|
ulong
|
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
|