using System; namespace Lesson7 { class program { static void Main(string[] args) { Console.WriteLine("类型转换—隐式转换"); //什么是隐式转换? //类型转换就是不同变量类型之间的转换 //隐式转换是指在不需要额外操作的情况下,编译器自动完成的转换。 //隐式转换规则:大范围装小范围 #region 知识点一 相同大类型之间的转换 //有符号 long->int->short->byte long l = 1; int i = 1; short s = 1; sbyte sb = 1; l = i; //int 转 long //i = l; long 转 int //小的类型不能装大的 需要强制转换,不能隐式转换 //可以的转换: l = i; l = s; l = sb; i = s; s = sb; //无符号 ulong->uint->ushort->byte ulong ul = 1; uint ui = 1; ushort us = 1; byte b = 1; //浮点数 double float decimal decimal de = 1.1m; double d = 1.1; float f = 1.1f; //decimal没有办法用隐式转换的形式去存储double和float //de = d; //de = f; d = f;//float 是可以转 double 的 //特殊类型 bool char string //他们之间不存在隐式转换 bool b1 = true; char c = 'a'; string str = "Hello World"; #endregion #region 知识点二 不同大类型之间的转换 #region 无符号装有符号 // 无符号 byte b2 = 1; ushort us2 = 1; uint ui2 = 1; ulong ul2 = 1; // 有符号 sbyte sb2 = 1; short s2 = 1; int i2 = 1; long l2 = 1; // 无符号装有符号 // 有符号的变量无法隐式转换为无符号的变量 eg:负数情况 //b2 = sb2; //us2 = sb2; // 有符号装无符号 // 无符号的变量可以隐式转换为有符号的变量 // 但需要注意的是,如果无符号变量的值大于有符号变量的最大值,则会发生溢出 //i2 = ui2; i2 = b2; #endregion #region 浮点数和整数之间(有符号、无符号)的转换 // 浮点数装整数 float f2 = 1.1f; double d2 = 1.1; decimal de2 = 1.1m; //浮点数可以装载任何类型的整数(有符号、无符号) f2 = l2; f2 = ul2; f2 = 1000000000000000000; // 1.0E+20 Console.WriteLine(f2); // 输出 1.0E+20 //decimal不能隐式存储浮点数 //但是可以隐式存储整数 de = l2; de = ul2; //double->float->所有整形 //decimal->所有整形 //整数是不能隐式存储浮点数的,因为浮点数有小数部分 //i2 = f2; // 错误,不能隐式转换 #endregion #region 特殊类型和其他类型之间的转换 // bool //bool bo2 = true; //bo2 = i2; //bo2 = ui2; //bo2 = f2; //i2 = bo2; //ui2 = bo2; //bool无法与其他类型隐式转换 // char char c2 = 'a'; //c2 = i2; //c2 = ui2; //c2 = f2; //c2 = str; //char 可以隐式转换为 整数类型 和 浮点型 //char转换后的值是其对应的ASCII编码值 i2 = c2; Console.WriteLine(i2); f2 = c2; Console.WriteLine(f2); ui2 = c2; Console.WriteLine(ui2); //str = c2; // string #endregion #endregion //总结: //隐式转换是编译器自动完成的转换,不需要额外操作。 //隐式转换规则:大范围装小范围,高精度装低精度 //double->float->所有整形->char //decimal不能隐式转换为浮点数,但可以隐式转换为整数。 //decimal->所有整形->char //bool、string不参与隐式转换。 } } }