当前位置:网站首页>is 和 as的用法

is 和 as的用法

2022-01-15 02:02:52 罗迪尼亚的熔岩

using System;

namespace _08_继承
{
    
    class Program
    {
    
        static void Main(string[] args)
        {
    
            int age = 18;
            char gender = '男';
            string name = "王五";
            double drive_time = 18.8;

            string interest = "偷拍";
            Driver_1 driv = new Driver_1(name, age, gender, drive_time);

            

            Reporter_ rep = new Reporter_(name, age, gender, interest);

            //里氏转换
            //1) 子类可以赋值给父类,如果有一个地方需要一个父类做参数,我们可以给一个子类代替
            Student_1 s = new Student_1(); //子类
            Person p = s;

            Person p = new Student_1();

            string str = string.Join("|", new string[] {
     "1", "2", "3", "4", "5", });

            Console.WriteLine(str); //1|2|3|4|5


            //2) 如果父类中装的是子类对象,那么可以将这个父类强转为子类对象

            if (p is Teacher_1)
            {
    
                Teacher_1 ss = (Teacher_1)p; //强制转换 异常
                ss.TeacherSayHello();
            }
            else
            {
    
                Console.WriteLine("转换失败");
                Console.ReadKey();
            }

             //is 的用法
            if (p is Student_1)
            {
    
                Student_1 ss = (Student_1)p; //强制转换
                ss.Xuesheng();
            }
            else
            {
    
                Console.WriteLine("转换失败");
                Console.ReadKey();
            }

            Student_1 t = p as Student_1; //p 是 student
            Teacher_1 t = p as Teacher_1; //把p父类对象转为teacher;
                                          //as 如果能转换,则返回一个对应的对象,否则返回NUll
                                          // t值为 null

            Student_1 t = p as Student_1; //可以成功
            Console.ReadKey();


            rep.Rep();
            driv.CHLSS();

        }
    }
}

版权声明
本文为[罗迪尼亚的熔岩]所创,转载请带上原文链接,感谢
https://blog.csdn.net/helldoger/article/details/121895339

随机推荐