006 C# 隐式转换和显式转换
1. 隐式转换
byte: 1位 = 8 bits
short: 2位 = 16bits
int: 4位 = 32bits
long: 8位 = 64bits
“短”可以转“长”;“长”转“短”则可能会丢失数据
byte b = 2;
int i = b; // 没问题,将 byte -> int
int i = 300;
byte b = i; // 报错:int不能隐式转换成byte
byte b = (byte)i; // 丢失数据,b 的值为44(因为抹去了高位数据)
2. 显式转换
string s1 = "123;
int i = Convert.ToInt32(s1); // 显式转换方法1
int i = int.Parse(s1); // 显式转换方法2
string s = "true";
bool b1 = Convert.ToBoolean(s2); // 显式转换方法1
bool b2 = bool.Parse(s2); // 显式转换方法2

浙公网安备 33010602011771号