C#的继承机制

C#的继承机制

继承是面向对象编程的重要概念之一,它允许我们根据一个类来定义另一个类,这让创建和维护应用程序变得更加容易,同时也利于代码重用和节省时间。
当创建一个类时,我们不需要完全重写新的数据成员和函数,只需要设计一个新的类,继承已有的类成员就可以了。这个已有的类就是基类,新的类就是派生类。
引用书上的:继承的思想实现了属于(IS-A)关系,例如哺乳动物 属于(IS-A) 动物,狗 属于(IS-A) 哺乳动物,因此狗 属于(IS-A) 动物。

假设,有一个基类 juxing,它的派生类是 mianji:

// An highlighted block
using System;
namespace InheritanceApplication
{
   class juxing 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // 派生类
   class mianji: juxing
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   
   class RectangleTester
   {
      static void Main(string[] args)
      {
         mianji Rect = new mianji();

         Rect.setWidth(4);
         Rect.setHeight(7);

         // 对象的面积
         Console.WriteLine("总面积: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }
}

当上面的代码被编译和执行时,它会产生下列结果:

代码执行

基类的初始化

派生类继承基类的成员变量和方法。因此父类对象应在子类被创建前创建,你可以在成员初始化列表中进行父类的初始化
下面代码演示了这一特点:

// An highlighted block
 namespace RectangleApplication
    {
        class Rectangle
        {
            // 成员变量
            protected double length;
            protected double width;
            public Rectangle(double l, double w)
            {
                length = l;
                width = w;
            }
            public double GetArea()
            {
                return length * width;
            }
            public void Display()
            {
                Console.WriteLine("长度: {0}", length);
                Console.WriteLine("宽度: {0}", width);
                Console.WriteLine("面积: {0}", GetArea());
            }
        }
        class Tabletop : Rectangle
        {
            private double cost;
            public Tabletop(double l, double w) : base(l, w)
            { }
            public double GetCost()
            {
                double cost;
                cost = GetArea() * 70;
                return cost;
            }
            public void Display()
            {
                base.Display();
                Console.WriteLine("成本: {0}", GetCost());
            }
        }
        class ExecuteRectangle
        {
            static void Main(string[] args)
            {
                Tabletop t = new Tabletop(4.5, 7.5);
                t.Display();
                Console.ReadLine();
            }
        }
    }

当上面代码被执行时回产生如下结果:

在这里插入图片描述

以上就是C#中的继承机制

多重继承

多重继承指的是一个类可以同时从大于一个父类继承行为与特征的功能。与单一继承相对,单一继承指一个类别只可以继承自一个父类。
C# 不支持多重继承。
但是接口可以通过接口来实现多重继承。
如想学习有关接口的知识请自行查阅书籍。

猜你喜欢

转载自blog.csdn.net/weixin_44538566/article/details/86770663