C#基础:类型转换(隐式转换和显示转换)

隐式转换,和显示转换 Checked (可能溢出时加上这个关键词)与unchecked

using System;
using System.Windows.Forms;
class Conversions
{
    static void Main()
    {
        int a=5;
        long  b;
        b=a;//隐式转换
        Console.WriteLine(b);
        long c=5;
        int d;
        d=(int)c;//显示转换
        Console.WriteLine(d);
        Console.WriteLine(int.MaxValue);
        Console.WriteLine(long.MaxValue);
        
        int e=5;
        long f=700000000000000000000;
        try{
            e=checked((int)f);
        }
        catch(System.OverflowException)
        {
            MessageBox.Show("发生溢出");
        }
    }    
}

 String型转换成int型的两种方法

age1 = Convert.ToInt32(Console.ReadLine());

age2 = int.Parse(Console.ReadLine());

1.1两种输出方式(加号连接输出和使用格式字符串输出)

Console.WriteLine("第一个人的姓名是" + name1 + ",年龄是" + age1 + "岁"); Console.WriteLine("第2个人的姓名是{0},年龄是{1}岁", name2, age2);

1.2输出的数据格式是制表形式,可以使用\t来控制

Console.WriteLine("姓名\t科目\t成绩");

综上述(1.1,1.2)

Console.WriteLine(""+name+" \t"+color+"\t"+star+"\t");

Console.WriteLine("{0}\t{1}\t{2}", name, color, star);

 

Parse()方法:将字符串转换成其他类型,用法为XXX.Parse(string);

Convert类:任何基本类型之间的相互转换

class Program

    {

        static void Main(string[] args)

        {

            double mydouble = 87.45;//原始数据

            int myint;

            float myfloat;

            string myString;

            myint = Convert.ToInt32(mydouble);

            myfloat = Convert.ToSingle(mydouble);

            myString = Convert.ToString(mydouble);

            string record = string.Format("转换后的整型数为{0}\t转换后的浮点型数为{1}\t转换后字符串型数为{2}", myint, myfloat, myString);

            Console.WriteLine(record);

            Console.ReadLine();

        }

    }

原文地址:https://www.cnblogs.com/lqsilly/p/2917402.html