这次我们首先讲解一下类型转换,我们在写程序时经常用到类型转换,而且特别多的规则。我在这里粗略的讲解一下.隐式转换是系统默认的、不需要加以声明即可进行的转换。
1.隐式数值转换
隐式数值转换实际上就是从低精度的数值类型转换到高精度的数值类型的转换。byte x=255;ushort y=x;y=65535;float z=y;//均从低精度到高精度,反之会产生溢出, 隐式数值转换的类型太多,我就不多介绍,记住上面的原则就可以了。详细规则可查看msdn
2.隐式枚举转换
隐式枚举转换用于把十进制整数0转换成任何枚举类型,对应的其他整数则不存在这种转换。
| using System; enum Color { Red,Green,Blue }; class MikeCat { static void Main() { Color c;//声明Color的变量c; c=0;//将0转换为Red; Console.WriteLine("c的值是{0}",c);//结果:c的值是Red;如果将c=0改成c=1,则编译器会给出错误。 } } |
| char c=(char)65;//A int i=(int)'A';//65 //显示转换包含所有的隐式转换,即任何系统允许的隐式转换写成显示转换的形式都是允许的。 int i=300; long l=(long)i; //另外一例: using System; class MikeCat { static void Main() { long longValue = Int64.MaxValue; int intValue = (int) longValue; Console.WriteLine("(int){0} = {1}", longValue, intValue); } } |
| /*test.cs*/ using System; public class MikeCat { public static void Main() { ushort u=65535; byte b=(byte)u; Console.WriteLine("b的值是{0}",b); } } 编译状况如下: E:/>csc test.cs Microsoft (R) Visual C# .NET 编译器版本 7.10.3052.4 用于 Microsoft (R) .NET Framework 版本 1.1.4322 版权所有 (C) Microsoft Corporation 2001-2002。保留所有权利。 E:/>test.exe b的值是255 E:/>csc/checked test.cs ///checked[+|-] 生成溢出检查 E:/>test.exe 未处理的异常: System.OverflowException: 算术运算导致溢出。 at MikeCat.Main() E:/>csc/checked- test.cs E:/>test.exe b的值是255 |

