C# 类型转换相关

        public void TypeConvert()
        {
            int a = 12;
            double b = 35.5;
            Console.WriteLine((int)b);//显示类型转换

            //使用convert、parse强制类型转换
            String s = "123";           
            int i = int.Parse(s);
            int j = Convert.ToInt32(s);
            Console.WriteLine("{0} {1}",i,j);

            //该方式也是将数字内容的字符串转换为int类型,但是该方式比int.Parse(string s) 好一些,它不会出现异常。最后一个参数result是输出值,如果转换成功则输出相应的值,转换失败则输出0。
            string s1 = "abcd";
            string s2 = "1234";
            int c, d;
            bool bo1 = int.TryParse(s1, out c);
            Console.WriteLine(s1 + " " + bo1 + " " + c);
            bool bo2 = int.TryParse(s2, out d);
            Console.WriteLine(s2 + " " + bo2 + " " + d);

            String str = "abc";
            char ch = 'a';
            Console.WriteLine(str.ToUpper());
            Console.WriteLine(b.ToString());
            Console.WriteLine(ch.CompareTo('d'));
        }

 

posted @ 2018-01-11 16:35  Rachel_Diary  阅读(91)  评论(0编辑  收藏  举报