C# 继承

23 篇文章 2 订阅
23 篇文章 0 订阅

C# 继承

继承是面向对象程序设计中最重要的概念之一。继承允许我们根据一个类来定义另一个类,这使得创建和维护应用程序变得更容易。同时也有利于重用代码和节省开发时间。

当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。这个已有的类被称为的基类,这个新的类被称为派生类。

基类和派生类

一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数

<访问修饰符符> class <基类>
{
 ...
}
class <派生类> : <基类>
{
 ...
}

实例

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("继承");
            gg hsq = new gg("哈士奇", "灰色", "骨头");
            mm bsm = new mm("波斯猫", "白色", "鱼");
            Console.ReadKey();

        }
    }
}

class DongWu
    {

        private string name { set; get; }
        private string color { set; get; }
        private string food { set; get; }
        public DongWu(string name, string color, string food)
        {
            this.name = name;
            this.food = food;
            Console.WriteLine("动物");
        }
    }

 class Gou:DongWu
    {

        public Gou(string name, string color, string food) : base(name, color, food)
        {
            Console.WriteLine("狗");
        }
    }
 class Mao : DongWu
        {
            public Mao(string name, string color, string food) : base(name, color, food)
            {
                Console.WriteLine("猫");
            }
        }
 class mm:Mao
    {
        public mm(string name, string color, string food) : base(name, color, food)
        {
            Console.WriteLine(name + ",白色"+",喜欢吃" + food);
        }
    }
 class gg:Gou
    {
        public gg(string name, string color, string food) : base(name, color, food)
        {
            Console.WriteLine(name +",灰色"+ ",喜欢吃" + food);
        }
    }

在这里插入图片描述

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值