在C#中
有符号的整型有:sbyte、short、int、long
无符号整型有:byte、ushort、uint、ulong
浮点型有:float、double、decimal
特殊类型:char、string、bool
对于隐式转换的规则
- 大范围可以存小范围的(无符号的不能存有符号的)
- double>float>整数(有符号、无符号)>char--(ASCII码值)
- decimal>整数(有符号、无符号)>char
- string和bool不参与隐式转换
对于显示转换 (强转)的规则
- 括号强转():一般将高精度转换为低精度,但是要注意精度问题与范围避免乱值。1.浮点数转为整数会丢失小数点。2.bool和string不参与()强转。
-
int a = 100; short b = 10; long c = 1000; uint x = 1; //a = b; //a = c;//不能小的存大的 a = (int)c; //x = b;//不能无符号的存有符号的 x = (uint)c; //c = x;
- Parse:将字符串转换为想要的类型。注意要符合规范。
int a = int.Parse("10"); int a = int.Parse("10.10");//10.10为浮点数不符合规范报错 int a = int.Parse("10000000000000");//超过int范围报错 float b = float.Parse("10.10"); bool c = bool.Parse("true"); char d = char.Parse("A");
- Convert:各个类型相互转化,填写的变量和常量必须正确否则出错。
int a = Convert.ToInt32("1212"); a = Convert.ToInt32('A'); a = Convert.ToInt32(13.12);//会进行四舍五入到整数 a = Convert.ToInt32(true);//值为1 a = Convert.ToInt32(false);//值为0 long b = Convert.ToInt64("453"); float c = Convert.ToSingle("12.21"); double d = Convert.ToDouble("12.21"); bool e = Convert.ToBoolean("true"); Console.WriteLine(e);//True char f = Convert.ToChar("A"); string g = Convert.ToString(145445);
- .ToString() :直接转变成字符串。
string a = 1.ToString(); string b = 11.1.ToString(); char c = 'A'; string d = c.ToString(); bool e = true; string f = e.ToString(); Console.WriteLine("你好" + 110 + true);//直接变为字符串