C# 里氏转换

子类可以赋值给父类
子类可以转换为父类
protected 修饰符 是让这个字段,在子类中也可以访问。设定访问权限。

using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 里氏转换


            // 类型并不一样    父 <= 子
            Person p1 = new Reporter("刘言", 26, '男');  // 子类 可以赋值给 父类

            // 类型转换:

            // 转换 父类 => 子类
            Reporter p3 = (Reporter)p1;
            p3.ReporterSayHello();

            // 判断检测:is as
            // 检查是否可转换 成功 true 失败 false 
            Person x1 = new Reporter("斜线", 22, '男');

            if (x1 is Reporter)
            {
                Console.WriteLine("成功");
                // 父类 转 子类 使用子类方法
                ((Reporter)x1).ReporterSayHello();
            }
            else
            {
                Console.WriteLine("失败");
            }

             检测是否可转换 成功 返回对象 失败 null
            //Reporter p4 = x1 as Reporter;


        }

    }
    // 人类 基础类
    public class Person
    {

        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _age;
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        private char _gender;
        public char Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }
        // 构造函数
        public Person(string name, int age, char gender)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
        }

    }
    // 派生类 1
    // 记者
    public class Reporter : Person
    {
        // 继承 父类 构造函数
        public Reporter(string name, int age, char gender) : base(name, age, gender)
        {
            this.Hobby = Hobby;
        }

        private string _hobby;
        public string Hobby
        {
            get { return _hobby; }
            set { _hobby = value; }
        }

        public void ReporterSayHello()
        {
            Console.WriteLine("姓名:{0},年龄{1},性别{2},我的职业{3}",
                this.Name, this.Age, this.Gender, this.Hobby);
        }
    }
    // 派生类 2
    // 老师
    public class teacher : Person
    {
        // 继承 父类 构造函数
        public teacher(string name, int age, char gender) : base(name, age, gender)
        {
            this.Prelection = Prelection;
        }

        private string _prelection;
        public string Prelection
        {
            get { return _prelection; }
            set { _prelection = value; }
        }

        public void PrelectionHello()
        {
            Console.WriteLine("姓名:{0},年龄{1},性别{2},我的职业{3}",
                this.Name, this.Age, this.Gender, this.Prelection);
        }
    }
}

你可能感兴趣的:(C#,学习,c#,开发语言)