C#实现继承

C#实现继承

如果一个类继承于另一个类的话,他会具有继承类的所有字段、属性和方法。
如下所示:

namespace InheritanceApplication
{
   class Shape :Object //基础类,除非继承别的类,否则所有的类都会派生于Object基类
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // 派生类
   class Rectangle: Shape              //派生于Shape类的Rectangle派生类
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   /*
   可以将Rectangle类想象成如下的形式:
   class Rectangle
   {
      ***************Object类*********************
      Object类体部分。。。。。。
      **********************************************
      加



      ***************Shape类部分***********************
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
      **********************************************
      加



      ***************Rectangle类部分*****************
      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();
      }
   }
}
//源码出处:https://www.runoob.com/csharp/csharp-inheritance.html

实现继承的访问权限问题

如果一个类被另一个类继承,那么会继承父类的所有数据和方法,但是访问不一定有权限。具体区别如下:

  • public 类内部可以,子类可以,其他类可以。
  • private 类内部可以,子类和其他类都不可以。
  • protected 类内部和子类可以,其他类不可以。
  • internal 类声明为内部的,即只有当前工程中的代码才能访问它。
发布了51 篇原创文章 · 获赞 0 · 访问量 891

猜你喜欢

转载自blog.csdn.net/weixin_40786497/article/details/103156293