2019.8.22 1.隐式转换&显示转换

1.显示转换:大的数值向小的转换

2.隐式转换:小的数值向大的转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;//隐式转换(小的数值范围向大的转换)
            long l = i;//隐式转换(小的数值范围向大的转换)

            C1 c1 = new C2();//隐式转换(小的数值范围向大的转换)

            //显示转换(通常是大的数值范围向小的转换)
            double d = 10.05;
            int iFromD = (int)d;

            C1 c11 = new C1();
            //C2 c2 = (C2)c11;//会报错无法强制转换


            try
            {
                C2 c2 = (C2)c11;
            }

            catch (Exception e){
                Console.WriteLine(e.Message);
            }
            //显示转换尾

            Console.WriteLine(c11 is C1);//是否为C1类型
            Console.WriteLine(c11 is C2);//是否为C2类型

            C2 c22 = c11 as C2;//把c11转换为C2类型 发现无法转换 返回null //as只能用于引用类型和非空类型
            Console.WriteLine(c22 == null);

            string sFormI = i.ToString();//ToString继承于Object几类,所有类型都有此方法

            int iFromS = Convert.ToInt32("100");//字符串转int 仅限数字 否则报错
            int iFromS2 = Int32.Parse("100"); //字符串转int 仅限数字 否则报错

            int iFrom3;
            bool succeed = Int32.TryParse("2344",out iFrom3);//试着去转换,有返回值如果非数字字符串转换会返回0
            Console.WriteLine(iFrom3);

            int? iNull = null; //可空类型

            Console.ReadLine();
        }
    }

    class C1 { }//隐式转换(小的数值范围向大的转换)
    class C2 : C1 { }//隐式转换(小的数值范围向大的转换)

}
原文地址:https://www.cnblogs.com/LiTZen/p/11397459.html