当前位置: 移动技术网 > IT编程>开发语言>c# > C# 继承

C# 继承

2020年04月24日  | 移动技术网IT编程  | 我要评论

c# 继承

继承(加上封装和多态性)是面向对象的编程的三个主要特性(也称为“支柱”)之一。 继承用于创建可重用、扩展和修改在其他类中定义的行为的新类。 其成员被继承的类称为“基类”,继承这些成员的类称为“派生类”。 派生类只能有一个直接基类。 但是,继承是可传递的。

基类和派生类

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

c# 中创建派生类的语法如下:

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

假设,有一个基类(父类) shape,它的派生类(子类)是 rectangle:

using system;
namespace inheritanceapplication
{
   class shape
   {
      public void setwidth(int w)
      {
         width = w;
      }
      public void setheight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // 派生类
   class rectangle: shape
   {
      public int getarea()
      {
         return (width * height);
      }
   }
   
   class rectangletester
   {
      static void main(string[] args)
      {
         rectangle rect = new rectangle();

         rect.setwidth(5);
         rect.setheight(7);

         // 打印对象的面积
         console.writeline("总面积: {0}",  rect.getarea());
         console.readkey();
      }
   }
}

基类(父类)的初始化

派生类继承了基类的成员变量和成员方法。因此父类对象应在子类对象创建之前被创建。您可以在成员初始化列表中进行父类的初始化。

using system;
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());
      }
   }//end class rectangle  
   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# 不支持多重继承。但是,您可以使用接口来实现多重继承。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网