2. 数值类型之间的相互转换
这里所说的数值类型包括 byte, short, int, long, fload, double 等,根据这个排列顺序,各种类型的值依次可以向后自动进行转换。举个例来说,把一个 short 型的数据赋值给一个 int 型的变量,short 值会自动行转换成 int 型值,再赋给 int 型变量。如下例:
private void TestBasic() { byte a = 1; short b = a; int c = b; long d = c; float e = d; double f = e; this.textBox1.Text = ; this.textBox1.AppendText(byte a = + a.ToString() + \n); this.textBox1.AppendText(short b = + b.ToString() + \n); this.textBox1.AppendText(int c = + c.ToString() + \n); this.textBox1.AppendText(long d = + d.ToString() + \n); this.textBox1.AppendText(float e = + e.ToString() + \n); this.textBox1.AppendText(double f = + f.ToString() + \n); }
编译顺利通过,运行结果是各变量的值均为 1;当然,它们的类型分别还是 System.Byte 型……System.Double 型。现在我们来试试,如果把赋值的顺序反过来会怎么样呢?在 TestBasic() 函数中追加如下语句:
int g = 1; short h = g; this.textBox1.AppendText(h = + h.ToString() + \n);
结果编译报错: G:\Projects\Visual C#\Convert\Form1.cs(118): 无法将类型“int”隐式转换为“short” 其中,Form1.cs 的 118 行即 short h = g 所在行。
这个时候,如果我们坚持要进行转换,就应该使用强制类型转换,这在 C 语言中常有提及,就是使用“(类型名) 变量名”形式的语句来对数据进行强制转换。如上例修改如下:
short g = 1; byte h = (byte) g; // 将 short 型的 g 的值强制转换成 short 型后再赋给变量 h this.textBox1.AppendText(h = + h.ToString() + \n);
编译通过,运行结果输出了 h = 1,转换成功。 但是,如果我们使用强制转换,就不得不再考虑一个问题:short 型的范围是 -32768 ~ 23767,而 byte 型的范围是 0 ~ 255,那么,如果变量 g 的大小超过了 byte 型的范围又会出现什么样的情况呢?我们不妨再一次改写代码,将值改为 265,比 255 大 10
short g = 265; //265 = 255 + 10 byte h = (byte) g; this.textBox1.AppendText(h = + h.ToString() + \n);
编译没有出错,运行结果却不是 h = 265,而是 h = 9。 因此,我们在进行转换的时候,应当注意被转换的数据不能超出目标类型的范围。这不仅体现在多字节数据类型(相对,如上例的 short) 转换为少字节类型(相对,如上例的 byte) 时,也体现在字节数相同的有符号类型和无符号类型之间,如将 byte 的 129 转换为 sbyte 就会溢出。这方面的例子大同小异,就不详细说明了。
|