c# 继承

继承 ( : )

继承允许在一个类中去使用另一个类中的数据,以达到代码复用
c#中叫做基类和派生类(等效于我们在其他语言中的父类和子类)
一个派生类拥有该基类的所有成员变量和成员方法
c#的继承是单继承(c++允许多继承)
不允许循环继承(相互继承)

简单的小例子看一下什么是继承

我们先定义一个形状类:

namespace Day04
{
   
    internal class Shape
    {
   
        public int width;
        public int height;

        public void setWidth(int width)
        {
   
            this.width = width;
        }

        public void setHeight(int height)
        {
   
            this.height = height;
        }
    }
}

定义一个矩形类并让它继承自形状类:

namespace Day04
{
   
    internal class Rectangle : Shape
    {
   
        public int getArea()
        {
   
            return width * height;
        }
    }
}

定义一个三角形类也继承自形状类:

namespace Day04
{
   
    internal class Triangle : Shape
    {
   
        public int getArea()
        {
   
            return (height * width / 2);
        }
    }
}

测试类:

using Day04;

internal class Program
{
   
    private static void Main(string[] args)
    {
   
        Rectangle rec = new Rectangle();
        rec.setHeight(5);
        rec.setWidth(10);
        Console.WriteLine(rec.getArea());

        Triangle tri 
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值