父类

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

namespace ConsoleStudy
{
    class Person
    {
        /// <summary>
        /// 类的构造函数 函数名与类名一致
        /// </summary>
        /// <param name="name"></param>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        public Person(string name, int age, char sex)
        {
            this.Name = name;
            this.Age = age;
            this.Age = age > 0 ? age : 0;
            this.Sex = sex == '女' ? '女' : '男';
        }

        string _name;
        int _age;
        char _sex;

        public string Name { get => _name; set => _name = value; }
        public int Age { get => _age; set => _age = value; }
        public char Sex { get => _sex; set => _sex = value; }

        /// <summary>
        /// 类方法 自我介绍
        /// </summary>
        public void Introduce()
        {
            Console.WriteLine("我叫{0},我今年{1}岁,我的性别{2}", this.Name, this.Age, this.Sex);
        }
    }
}

子类

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

namespace ConsoleStudy
{
    class Programmer : Person
    {
        /// <summary>
        /// 继承父类的构造函数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="age"></param>
        /// <param name="sex"></param>
        /// <param name="workType"></param>
        public Programmer(string name, int age, char sex, string workType) : base(name, age, sex)
        {
            this.WorkType = workType;
        }

        string _workType;

        public string WorkType { get => _workType; set => _workType = value; }

        /// <summary>
        /// 隐藏父类的方法 改成为自己的方法
        /// </summary>
        public new void Introduce()
        {
            Console.WriteLine("我叫{0},我今年{1}岁,我的性别{2},我的工作是{3}", 
                this.Name, this.Age, this.Sex, this.WorkType);
        }
    }
}

调用

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

namespace ConsoleStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person("张三", 20, '男');
            person.Introduce();

            Programmer programmer = new Programmer("李四", 21, '男', "C#工程师");
            programmer.Introduce();


            Console.ReadKey();
        }
    }
}

VS2017打开类图

C#继承

C#继承

查看类图

C#继承

C#继承

相关文章:

  • 2021-11-22
  • 2021-07-30
  • 2021-12-26
  • 2021-07-13
  • 2021-04-12
  • 2021-05-25
猜你喜欢
  • 2021-07-05
  • 2021-08-27
  • 2021-09-25
  • 2022-12-23
  • 2021-07-07
  • 2021-10-23
  • 2021-06-30
相关资源
相似解决方案