C#继承

本文探讨了C#中的继承概念,从父类到子类的详细解释,包括如何创建和调用继承的类。此外,还介绍了如何在Visual Studio 2017中使用类图工具来可视化和查看继承结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父类

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打开类图

查看类图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值