2024-11-14《继续c#学习》

今天进行了C#的学习,继续了解C#的相关知识:

 

 

继承

  继承就是基类派生出去多种类,就好比狗是哺乳动物,狗是派生类,哺乳动物是基类。

  下面是一个简单的继承:

  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 InheritanceApplication
  {
  class Shape
  {
  public void setWidth(int w)
  {
  width = w;
  }
  public void setHeight(int h)
  {
  height = h;
  }
  protected int width;
  protected int height;
  }
   
  // 基类 PaintCost
  public interface PaintCost
  {
  int getCost(int area);
   
  }
  // 派生类
  class Rectangle : Shape, PaintCost
  {
  public int getArea()
  {
  return (width * height);
  }
  public int getCost(int area)
  {
  return area * 70;
  }
  }
  class RectangleTester
  {
  static void Main(string[] args)
  {
  Rectangle Rect = new Rectangle();
  int area;
  Rect.setWidth(5);
  Rect.setHeight(7);
  area = Rect.getArea();
  // 打印对象的面积
  Console.WriteLine("总面积: {0}", Rect.getArea());
  Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
  Console.ReadKey();
  }
  }
  }

posted @   new菜鸟  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示