C#中的类型转换

隐式类型转换

class Demo
    {
        //隐式类型转换
        static void Main() {
            double num = 3.12;
            double result = num + 2;

            Console.WriteLine(result);
            Console.ReadLine();

            //考一考
            //bool flag;
            //char ch;
            //short s_val;
            //int i_val;
            //float f_val;
            //double d_val;

            //1.2+'A' ==>'A'->double
            //d_val + i_val ==>i_val->double
            //flag +d_val【error】
            //s_val+ch; ==>s_val->int,ch->int
            //f_val+ch;==>ch->float
            //flag+ch;【error】
            //d_val+f_val;==>f_val->double
        }
    }

显式类型转换

class Demo
    {
        //显式类型转换
        static void Main() {
            double num = 83.5;
            int score = (int)num + 2;

            double a = 8.555;
            int c = Convert.ToInt32(a);

            //只针对数值类型
            int d = int.Parse(a.ToString());

            Console.WriteLine(c);
            Console.ReadLine();
        }
    }

你可能感兴趣的:(.net)