C#隐式转换与显示转换

在C#中

有符号的整型有:sbyte、short、int、long

无符号整型有:byte、ushort、uint、ulong

浮点型有:float、double、decimal

特殊类型:char、string、bool

对于隐式转换的规则 

  1. 大范围可以存小范围的(无符号的不能存有符号的)
  2. double>float>整数(有符号、无符号)>char--(ASCII码值)
  3. decimal>整数(有符号、无符号)>char
  4. 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);//直接变为字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值